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

I want to call two functions when myValue changes, and although this works very well:

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

in this case no function is called:

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

For me, this is not very important if I cannot name both functions within the same event with changes, as it is now, but I'm pretty new to jQuery and would like to know why.

+5
source share
4 answers

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

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

Pay attention to the final () .

+6
source

Use your own 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 specific context, and this works when it refers to the returned function, but not the way you do it in the callback, since the returned function is never called.

Of course you can use $.proxy and just call the returned function

 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); 
+3
source

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

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

The call function calls the function, and you need to go into the "context", i.e. which is used as 'this' inside a function, as in $ .proxy.

+3
source

Why can't you call it simple?

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

All Articles