Backbone is an excellent front-end MVC library.CodeThe quality must be reliable. The triggerevents function is interesting during reading. At first glance, some code is redundant.
VaR triggerevents = function (events, argS) {var eV, I =-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 );}};
This section is the core function for dispatching events in backbone. Events. The execution sequence is probably
- Extract and execute event processing functions in sequence
- Branch processing based on the length of the second ARGs Parameter
- Call is used when ARGs length is 3 or less, and apply is used when length is 3 or more
If you remove all calls and use apply directlyProgramThe logic is correct. As follows:
VaR triggerevents = function (events, argS) {var eV, I =-1, L = events. length; while (++ I <L) (EV = events [I]). callback. apply (ev. CTX, argS );};
The Code is also streamlined. The preceding call code is added to backbone. Let's see the comment.
// A difficult-to-believe, but optimized internal dispatch function for // triggering events. tries to keep the usual cases speedy (most internal // backbone events have 3 arguments ).
Although hard to believe, it is for performance considerations. When most backbone internal methods trigger an event, three parameters are passed, that is, call (rather than apply) is used ).
According to this reasoning, the call performance is higher than that applied. The keyword "Call apply performance" seems to have confirmed this statement.
This is a test on jsperf.com.
From the test results, we can see that the call performance in most browsers is better than the apply performance, and only the safari5 and safari6 have similar performance. Therefore, backbone exchanges redundant code for runtime performance.
Note: backbone 1.0
Related:
Http://jsperf.com/call-apply/3
What-is-the-difference-between-call-and-apply
Why-are-call-and-apply-slower-than-a-direct-function-call-in-Javascript