javascript - Backbone triggerEvents -


i reading backbone.js sourcecode events module , code got me confused:

var triggerevents = function(events, args) {    var ev, = -1,      l = events.length,      a1 = args[0],      a2 = args[1],      a3 = args[2];    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, a1);        return;      case 2:        while (++i < l)(ev = events[i]).callback.call(ev.ctx, a1, a2);        return;      case 3:        while (++i < l)(ev = events[i]).callback.call(ev.ctx, a1, a2, a3);        return;      default:        while (++i < l)(ev = events[i]).callback.apply(ev.ctx, args);        return;    }  };

i'm wondering why should determine args.length? why not write that:

var triggerevents = function(events, args) {      var ev, = -1,      while (++i < l)(ev = events[i]).callback.apply(ev.ctx, args);    };

so main question : why should determine args.length? why not use 1 while (++i < l)(ev = events[i]).callback.apply(ev.ctx, args); replace call?

this "educated guess" (without knowing backbone internals) seems each event has callback property, function called, when event triggered. click example.

this callback function can take various number of arguments. number of arguments not known. that's args.length kicks in. when pass single argument, call callback function single argument. if call 2, pass 2 arguments, etc...

the reason why there callback.call() , callback.apply() because .call() passes arguments invoked function "one-by-one" whereas .apply() passes arguments single array.

good explanation of difference between .call() , .apply() can found in article http://hangar.runway7.net/javascript/difference-call-apply

ps: correct me if guess backbone wrong :)

update

there comment in source code https://gist.github.com/badsyntax/4663217, above triggerevents declaration. answer. can try find perf tests :)

   // optimized internal dispatch function triggering events. tries    // keep usual cases speedy (most backbone events have 3 arguments). 

update 2

the reason optimization .call() can faster .apply(), because .apply() needs construct array argument. (and calling .call() , .apply slower calling original method, because there 1 more operation perform)


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -