gpt4 book ai didi

javascript - 从 Backbone.js 中的 View 取消绑定(bind)模型

转载 作者:行者123 更新时间:2023-11-29 22:20:50 25 4
gpt4 key购买 nike

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

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

一旦我离开这个 View ,我想解除事件与这个 View 的绑定(bind)。我为此尝试过这样

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

不过好像没什么效果。我怎样才能在 backbonejs 中正确地做到这一点?谢谢

最佳答案

您的代码存在问题,您使用 _.bind 绑定(bind)/取消绑定(bind)。因为这将始终创建一个新功能。所以你绑定(bind)的函数和你尝试解除绑定(bind)的函数是不一样的,所以解除绑定(bind)是行不通的。

您必须保存对您绑定(bind)的函数的引用,或者在开始时使用 _.bindAll 因为这会将您当前的函数替换为绑定(bind)的函数。所以当你使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com