TriggerEvents main variable

I am reading the Backbone.js source and am confused about this

var triggerEvents = function(events, args) {
  var ev, i = -1, l = events.length;
  switch (args.length) {
    case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx);
    return;
    case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0]);
    return;
    case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1]);
    return;
    case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, args[0], args[1], args[2]);
    return;
    default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args);
  }
};

      

I have a number of questions -

  • Why is this an optimization for firing events (as the annotated source says)?
  • What is ev.ctx?
  • What is .callback ()?

This structure implies that if given a chance, always use invocation rather than enforce in the interest of speed, as the structure of this function seems to say, "If I know how many arguments there are using invocation, use apply instead" when you can just use it all to the end.

In short, I don't know what the purpose of this function is and why it is written the way it was written, and if someone can tell me that would be great!

0


source to share


1 answer


I created a small JSPerf benchmark suite that compares performance to Function.call

and Function.apply

. It shows quite clearly that (with Chrome 24) Function.call

it is 30-50% faster. Try running it in your browser to see how the performance differs.

This does not mean, however, that you should follow this optimization in your own code. Backbone event functionality is at the heart of Backbone and many events are fired. The authors have optimized this piece of code to squeeze the last bit of performance out of it. In most other cases, this will be over-optimization.

The property ev.callback

is the callback function for the event.

Consider the following example:

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

      



The callback in this case is a method this.handleChange

.

The notation (ev = events[i]).callback.call

is just a shortcut to

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

      

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

On the other hand, a property ev.ctx

is an object to bind as a context this

to a callback function. Backbone.Events.on

takes context as an optional argument. In the above example, the last argument this

indicates that the context of the callback function should be a class.

+3


source







All Articles