问题描述
var PlaylistView = Backbone.View.extend({
el: '#expanded-container',
initialize: function() {
var playlistModel = this.model;
this.stopListening(playlistModel.get('songs'), 'add');
var form = this.$('input');
$(form).keypress(function (e) {
if (e.charCode == 13) {
console.log("hey")
var query = form.val();
playlistModel.lookUpAndAddSingleSong(query);
}
});
this.listenTo(playlistModel.get('songs'), 'add', function (song) {
var songView = new SongView({ model: song });
this.$('.playlist-songs').prepend(songView.render().el);
});
这是我的Backbone视图的一小段,我无法弄清楚为什么有时相同的songView
会被渲染两次.在其他视图中,我手动调用PlaylistView.initialize()
而不重新创建视图.因此,我在初始化开始时注销了所有事件,以防止它多次侦听同一事件.它完成了它的工作,但仅偶尔执行一次,同一SongView被渲染两次.我怀疑这可能是某种竞赛情况,但我无法弄清原因.有人有主意吗?
This is a snippet of my Backbone view and I cant figure out why sometimes the same songView
is rendered twice. In other view, I call PlaylistView.initialize()
manually without recreating the view. Because of that, I deregister all the events in the beginning of initialize to prevent it from listening to the same event multiple times. It does its job but only once in a while, the same songView is rendered twice. I suspect this might be some kind of a race condition but I haven't been able to figure out the reason. Does anyone have an idea?
推荐答案
如果playlistModel.get('songs')
没有返回相同的对象,则可能会发生这种情况,请尝试仅删除事件,无论对象是什么,如下所示:
That may happen if playlistModel.get('songs')
are not returning the same objects, try to remove only the event whatever the objects are, like this:
this.stopListening(null, 'add');
这篇关于stopListening()竞赛条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!