Possible Duplicate:
Javascript closure inside loops - simple practical example
Recently I have been playing around with some of the more complicated aspects of JavaScript, one of which is design patterns and delegation.
I have created a object containing 2 keys, which I then parse and attach an event onto the body.
My problem is that it seems like the last function is attached for any iteration of the for loop. I am pretty sure this is a copy by reference/scoping(thanks Shmiddty) problem, but please correct me if I am wrong.
Is there anyway to fix my issue to attach the 2 events on properly without changing too much? (As this is a complex app that I have simplified down to the issue at hand).
On the jsfiddle example please see how the alert message for .div1
is the same as .div2
var foo = {
init: function() {
var i = 0,
keys = []
self = this;
for (var key in this) {
keys.push(key);
}
for (i; i < keys.length; i++) {
if (keys[i].match(/^on/i)) {
var delegateFunc = keys[i].split(' | '),
event = delegateFunc[2],
selector = delegateFunc[1],
keyName = keys[i];
console.log('###');
console.log( 'selector: ' + selector );
console.log( 'event: ' + event );
console.log( 'function: ' + self[keyName] );
$('body').on(event, selector, function(ev) {
self[keyName](ev, ev.target);
});
}
}
},
'on | .div1 | click': function(ev, el) {
alert('you clicked 1');
},
'on | .div2 | click': function(ev, el) {
alert('you clicked 2');
}
}
$(function() { foo.init(); });
Any more info needed? Leave me a comment. Cheers