I think this question is more a javascript question than a backbone question, but I’ve run into it while developing an application in backbone, so that’s the context I will ask it in.
I am binding a method with arguments to a model’s change event. The code below executes that method when the listener is bound, not when the event is fired:
this.model.on("change:disposition", this.dChange("disposition"), this);
while the following code executes the method when the change event is fired (the desired behavior):
this.model.on("change:disposition", function(){ this.dChange("disposition"); }, this);
I would appreciate it if someone could describe what specifically is happening in these two instances. Also, is there is a better way to bind a method with arguments rather than wrapping it in a closure as I’ve done?
Thanks.
When you call
this.dChange("disposition")you’re invoking the function. (You’re using the parentheses()to invoke)But when you do
function() {}orthis.dChangeyou’re in fact referencing a function object. And it’s this reference that the event manager will call once the event is fired.Side note: In your case, instead of using an anonymus function, you could use the bind method of Underscore.js like this: