Note that there are some explanatory texts on larger screens.

plurals
  1. POPrototype vs jQuery: A specific problem regarding binding, events and values
    primarykey
    data
    text
    <p>I'm looking at transferring existing functionality (built with PrototypeJS) to jQuery and have been working through a couple of examples.</p> <p>One example I'm a bit stuck on, specifically with regards to binding functions (and values) to an event. This example tries to apply a mouseover event, with an incremented value to a list of links. The value that is alerted I want to be the same every time (so link 1 alerts "1", link 2 alert "2" etc etc)</p> <p>Here's a snippet of a simple example.</p> <p>Prototype:</p> <pre><code>findLinks: function () { i = 1; $$("#vertical-content-links ul li a").each(function (s) { Event.observe(s, "mouseover", this.activateLink.bindAsEventListener(this, i)) i++ }.bind(this)) }, activateLink: function (e, i) { alert(i) } </code></pre> <p>Within this example, when link 1 is mouseovered, it will always alert "1". Link 2 will always alert "2" etc etc as it is alerting the value of i when the function is applied to that event.</p> <p>However, my similar code in jQuery....</p> <pre><code>findLinks: function () { i = 1; $("#vertical-content-links ul li a").each(function (s, elmt) { $(elmt).bind("mouseover", function (e) { _this.activateLink(i); i++ }) }) }, activateLink: function (i) { alert(i); } </code></pre> <p>(Note: _this is a closure specified elsewhere in the code)</p> <p>When this runs, every time a link is mouseovered, the value of i is incremented by one, so link 1 will alert 1, then 2,3,4,5 etc as the value of i doesn't seem to be bound to the function when it is applied to the event</p> <p>Hope that makes sense</p> <p>Does anyone know a way around this so it works more the way Prototype does. I really want to start using jQuery more but need to understand this issue first.</p> <p>Cheers</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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