I have started learned BackBone.js. Currently my javaScript skill is not very well. I have started examine bacjbone.js file and have seen strange line of code that purpose I can not figure out. Code sample (you manully download backbone.js for developers and see 80 line):
var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; },
What line this._events || (this._events = {}); means? For me _events looks like inner variable, but what the progit to call assigment (this._events = {}) and make or comparisson? Or || mean another operation?
It is a trick that uses javascripts "falsy" evaluation. It is the same as:
if (this._events) { // do nothing, this._events is already defined } else { this._events = {}; } The same goes for the line var events = this._events[name] || (this._events[name] = []); which could be translated to
var events; if (this._events[name]) { events = this._events[name]; } else { this._events[name] = []; events = this._events[name]; }It's shorthand for conditional assignment. This code will assign an empty Javascript object to the Backbone.Events._events variable if it doesn't already have a value.
It makes use of a practice called boolean short-circuiting. null evaluates as false, and the right-hand expression in the or statement will not be evaluated because the left-hand is already true.
What line “this._events || (this._events = {});” means?
In essence it checks if this._events is falsy and if so then assign a new empty object to it.
The conditional OR (||) executes the first expression this._events and if falsy executes the second expression (this._events = {}).
It's a way to write
if (!this._events) { this._events = {}; } In my opinion it's bad practice to use that kind of short hand, and I think the following line
var events = this._events[name] || (this._events[name] = []); is even worse. Mixing assignment, of the events with the creation of this._events[name] is quite short, but it's also hard to read. If you don't know what you're doing you might introduce subtle errors that way. That doesn't outweigh the benefits of having it all in one line.
And in the end it will be minified anyway. Let the minifiers take care of stuffing everything in one line. No need to do it yourself.
No comments:
Post a Comment