Zach
Zach

Reputation: 10139

Unbind model from view in Backbone.js

I have an audio player class which controls the HTML5 audio player. In that I am monitoring the the audio player events and triggering them to the associated view. On the view file this is how I bind the appropriate events

app.audioPlayer.$el.bind('musicEnded', _.bind(this.onMusicEnded, this));
app.audioPlayer.$el.bind('askForNextMusic', _.bind(this.onAskForNextMusic, this));
app.audioPlayer.$el.bind('askForPreviousMusic', _.bind(this.onAskForPreviousMusic, this));

Once I move out from this view I want to unbind the events from this view. I tried like this for that

app.audioPlayer.$el.unbind('musicEnded', _.bind(this.onMusicEnded, this));
app.audioPlayer.$el.unbind('askForNextMusic', _.bind(this.onAskForNextMusic, this));
app.audioPlayer.$el.unbind('askForPreviousMusic', _.bind(this.onAskForPreviousMusic, this));

But it dosent seems to have any effect. How can I properly do this in backbonejs? Thanks

Upvotes: 2

Views: 755

Answers (2)

Andreas Köberle
Andreas Köberle

Reputation: 110932

The problem with your code is, that you bind/unbind using _.bind. As this will always create a new function. So the function you bind and the function you try to unbind are not the same, so unbind will not work.

You have to save a reference to the function you bind, or use _.bindAll in the beginning cause this will replace you current function with a binded one. So when ever you use bind/unbind then it is the same function:

_.bindAll(this, onMusicEnded) 
// the will replace this.onMusicEnded with _.bind(this.onMusicEnded, this)
app.audioPlayer.$el.bind('musicEnded', this.onMusicEnded);
app.audioPlayer.$el.unbind('musicEnded', this.onMusicEnded);

Upvotes: 2

Array out of bound
Array out of bound

Reputation: 1133

http://backbonejs.org/#Events

Bind a callback function to an object. The callback will be invoked whenever the event is fired.

object.on(event, callback, [context])

Remove a previously-bound callback function from an object.

object.off([event], [callback], [context])

Upvotes: 0

Related Questions