6

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.

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, that took me a while to spot :)
Mmh, why not just self.functionOne()? ;)
3

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.

Comments

3

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);

Comments

0

Why can't you call it simple like this?

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

3 Comments

i guess this != self
What makes you think he functions are available in the current scope?
good point @FelixKling but,, isn't he proxying to self,, or current scope?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.