Skip to content Skip to sidebar Skip to footer

Backbone TriggerEvents Variable

I'm reading through the Backbone.js source and am confused by this var triggerEvents = function(events, args) { var ev, i = -1, l = events.length; switch (args.length) { ca

Solution 1:

I created a small JSPerf test suite that compares Function.call and Function.apply performance. It shows quite clearly that (with Chrome 24) Function.call is faster by 30-50%. Try and run it in your browser to see how the performance differs.

This doesn't mean, however, that you should follow this optimization in your own code. The Backbone events functionality is at the core of Backbone, and a lot of events are fired. The authors have optimized this piece of code to squeeze the last bits of performance out of it. In most other cases this would be an over-optimization.

The ev.callback property is the callback function for the event.

Consider the following example:

this.model.on('change', this.handleChange, this);

The callback in this case is the this.handleChange method.

The notation (ev = events[i]).callback.call is just a shortcut for

ev = events[i];
ev.callback.call

The shortcut works, because in javascript an assignment operation returns the assigned value.

The ev.ctx property on the other hand is the object to bind as the this context to the callback function. Backbone.Events.on takes the context as an optional argument. In the above example the last argument, this, specifies that the callback function's context should be the containing class.


Post a Comment for "Backbone TriggerEvents Variable"