Wednesday, 21 August 2013

Common JavaScript Closure issue on jQuery elements in an Array

Common JavaScript Closure issue on jQuery elements in an Array

I am working at building a widget that calls a particular plugin on each
jQuery DOM element inside an array.
MyApp.forms is an array of Objects. Each Object has a jQuery wrapped DOM
element.
I am doing the following:
$(MyApp.forms).each(function(i){
var individualForm = this;
/*
individualForm is an Object {
prop: 'value,
$el: somejQueryElement,
...
}
*/
individualForm.$el.on('something', function() {
individualForm; // refers to the last object in MyApp.forms
this; // refers to the last
$(this); // same problem
}).on('somethingElse', function() {
// same problem as above here.
});
});
The events something and somethingElse get attached to all
individualForm's $el. But when they fire, I always get the last element.
I feel this is a common JavaScript Closure problem.
I tried using a for loop and creating an IIFE inside but it doesn't work,
as the function executes when the event fires. And though both events fire
on all elements, I only get the handler attached to last element executed.

No comments:

Post a Comment