Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling multiple functions from within jQuery .on("change"... event)

I want to call two functions when myValue changes, and while this works just fine:

this.myValue.on("change", $.proxy(self.functionOne, self));
this.myValue.on("change", $.proxy(self.functionTwo, self));

neither function is called in this case:

this.myValue.on("change", function () {
    $.proxy(self.functionOne, self);
    $.proxy(self.functionTwo, self);
})

It isn't a huge deal to me if I can't call both functions within one change event like this right now, but I'm pretty new to jQuery and would like to learn why.

like image 826
LarsHoffbeck Avatar asked Apr 16 '15 12:04

LarsHoffbeck


2 Answers

You need to call the functions defined in the $.proxy():

this.myValue.on("change", function () {
    $.proxy(self.functionOne, self)();
    $.proxy(self.functionTwo, self)();
})

Note the trailing ().

like image 55
Rory McCrossan Avatar answered Oct 01 '22 04:10

Rory McCrossan


The $.proxy method will just return a function, but not call it. You can use:

self.functionOne.call(self);
self.functionTwo.call(self);

The call function calls the function, and you get to pass in the 'context' ie. what gets used as 'this' within the function, much like in $.proxy.

like image 25
graycodes Avatar answered Oct 01 '22 04:10

graycodes