我有一个控制HTML5音频播放器的音频播放器类。在此,我正在监视音频播放器事件,并将它们触发到关联的视图。在视图文件上,这是我绑定适当事件的方式

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


从该视图中移出后,我想取消该视图中的事件绑定。我为此尝试了

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


但是它似乎没有任何作用。我怎样才能在骨干js中做到这一点?
谢谢

最佳答案

代码的问题是,您使用_.bind进行绑定/取消绑定。因为这将始终创建一个新功能。因此,您绑定的功能和您尝试解除绑定的功能是不同的,因此解除绑定将不起作用。

您必须保存对绑定函数的引用,或者在开始时使用_.bindAll,因为这将用绑定的函数替换当前函数。因此,无论何时使用bind / unbind,它都是相同的功能:

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

关于javascript - 从Backbone.js中的 View 解除绑定(bind)模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12529511/

10-12 12:46
查看更多