Will
Will

Reputation: 5590

jQuery - adding dynamic data to a event binding

I have an event binding that looks like this:

$('#form').on('submit', { callback : Obj.method }, FunctionName);

The binding runs on page load, however, at that time Obj.method is not defined -- I had thought that it used whatever the current value of Obj.method was, but it apparently uses whatever value it has at the time it runs.

Is there a way to have the data determined at the time the event handler fires? My guess at this point is no ... but people here seem to know a lot more then I do.

Upvotes: 0

Views: 243

Answers (2)

jfriend00
jfriend00

Reputation: 707736

If it's a variable that exists at the time the event handler fires and you want it evaluated then, you can just reference it directly from the handler function:

$('#form').on('submit', function(e) {
    FunctionName(Obj.method);
});

or, if you just want it called directly:

$('#form').on('submit', function(e) {
    Obj.method();
});

Upvotes: 1

Paolo Bergantino
Paolo Bergantino

Reputation: 488564

Just wrap the callback with a function and it won't be run until the callback fires.

$('#form').on('submit', {
    callback : function() {
        Obj.method();
    } 
}, FunctionName); 

Upvotes: 2

Related Questions