I’m sort of emulating Backbone’s event system with an object like this:
var events = {
'click .one': 'fnOne',
'click .two': 'fnTwo',
'click .three': 'fnThree'
}
Then to set the event listeners with jquery I’m using the following:
var method,
match,
event_name,
selector;
var scope = {
// Complex object literal passed to the event's
// function for access...
};
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
for (key in events) {
if (events.hasOwnProperty(key)) {
method = events[key];
match = key.match(delegateEventSplitter);
event_name = match[1];
selector = match[2];
$('#element').on(event_name,selector,function(event){
method(event,scope);
});
}
}
The problem I’m having is that it’s binding correctly except all of the events fire the last function fnThree
Just a closure/loop problem. A closure only binds lexical names, not the values at the time.
One of my favorite ways to capture values is
with:But this causes some acolytes of Doug Crockford to die of heart attack so you can also do:
I’ll let you decide which you find preferable.