Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Each event handler function you create in this code:</p> <pre><code>setHandlesByList: function (list) { for (var i in list) { var self = this; $(document).on(list[i].name, function (e) { list[i].callBack.call(self,e) }); }; }, </code></pre> <p>...has an <strong>enduring reference</strong> to <code>list</code> and <code>i</code>, not <em>copies</em> of them as of when the function is created. Since <code>i</code> ends up being the last property enumerated, all handlers end up referring to the same list entry.</p> <p>Instead, create a builder function to create the callback <em>(sorry, I can't recreate the indentation style you use, I've just used a fairly standard one)</em>:</p> <pre><code>setHandlesByList: function (list) { var self = this; for (var i in list) { $(document).on(list[i].name, buildHandler(list[i])); }; function buildHandler(entry) { return function (e) { entry.callBack.call(self,e) }; } }, </code></pre> <p>Now, the function created closes over <code>entry</code>, the argument to the <code>buildHandler</code> call, rather than over <code>list</code> and <code>i</code>. Since <code>entry</code> (the argument) doesn't change, the handler works.</p> <p>Note also that I've moved the <code>var self = this;</code> out of the loop, as it didn't vary from iteration to iteration and so had no business being in the loop.</p> <hr> <p>Side note: You've said that the function receives an <strong>array</strong>. If so, <code>for-in</code> (with no safeguards) is not the correct way to loop through the entries in that array. More: <a href="http://blog.niftysnippets.org/2010/11/myths-and-realities-of-forin.html" rel="nofollow"><em>Myths and realities of <code>for..in</code></em></a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload