I have something like this code:
for (var i = 0; i < interactions.length; i++) {
action = interactions[i].split(':');
if (events.indexOf(action[0]) >= 0) {
$(this).bind(action[0], function (e) {
if (action.length == 2) {
model[action[1]]();
}
else if (action.length == 3) {
var args = action[2].split('|');
model[action[1]].apply(null, args);
}
});
}
}
The variable “events” is simply a string with event names like ‘click,dblclick’ etc… The issue is when I get inside the event, the “action” variable is losing context. This appears to be a closure like construct in which “action” should stay in context but it doesn’t. In this example I have two interactions as in:
1) click:Save
2) disabled:SomeCustomFunction
So, when I perform a click event, I would expect action[1] to be “Save” but it’s actually “disabled”. So, it’s like whatever it was last set to, thats what I get.
Any ideas how to keep things in context?
Thanks so much,
By the time the event handler runs (when a click or whatever actually happens)
actionwill be equal to whatever it was on the last iteration of theforloop. Ifactionwas a local variable in a function called on each iteration then you’d get the closure construct you need.Since you are using jQuery already the easiest change is to use
$.each()instead of a plainforloop, thus putting the processing of each iteration into its own closure with its ownaction: