Infinity
Infinity

Reputation: 3875

Backbonejs and Custom Model Event

I am trying to create a custom event for my model but apparently the custom event get triggered no matter what unless I use "anonymous" function definition as a callback

Here is the pseudo code of my app structure

//Router
initialize: ->
  this.user = new User()
  this.view = new View({model:this.user})
  this.view.render()

//View
initialize: ->
  //This event binding get triggered no matter what
  //this.model.on("custom:event", this.triggerMe(), this) 

  //This works properly. Only triggered when I call model.trigger("custom:event")
  this.model.on("custom:event", function(){console.log("I WORK!!");}))

triggerMe: ->
  //I GET TRIGGER NO MATTER WHAT

Upvotes: 1

Views: 1539

Answers (2)

Simon Boudrias
Simon Boudrias

Reputation: 44589

By passing this.triggerMe() you automatically execute the triggerMe function (because you add parentheses, and by so invocating it).

What you need to do, is to pass a reference to the function. Like so:

this.model.on("custom:event", this.triggerMe, this)

Upvotes: 1

Mark
Mark

Reputation: 5720

you are invoking a function here:

this.triggerMe()

it should be this.triggerMe

this.model.on("custom:event", this.triggerMe, this)

Adding () or .call() or .apply() is invoking a function not a reference to it.

Upvotes: 4

Related Questions