LarsHoffbeck
LarsHoffbeck

Reputation: 107

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.

Upvotes: 6

Views: 3014

Answers (4)

adeneo
adeneo

Reputation: 318182

Use the native apply or call instead

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

$.proxy takes a function and returns a new one that will always have a particular context, and that works when the returned function is referenced, but not the way you're doing it in the callback as the returned function is never called.

You could of course use $.proxy and just call the returned function as well

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

or just let jQuery handle it, it optimizes events and uses an internal queue anyway

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

Upvotes: 3

Kresimir Pendic
Kresimir Pendic

Reputation: 3614

Why can't you call it simple like this?

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

Upvotes: 0

graycodes
graycodes

Reputation: 363

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.

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337560

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 ().

Upvotes: 8

Related Questions