javascript 骨干集合获取不会触发 reset()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15603107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:22:24  来源:igfitidea点击:

backbone collection fetch doesn't fire reset()

javascriptjquerybackbone.jsunderscore.js

提问by David Fregoli

This is my view for a collection

这是我对收藏的看法

var mssg = mssg || {};

mssg.MessagesView = Backbone.View.extend({

el: '#messages',

initialize: function() {
    this.collection.fetch();
    this.collection.bind('reset', this.render, this);
},

render : function() {
    this.$el.html('');
    this.collection.each(function( item ) {
        this.renderMessage( item );
    }, this );
    return this;
},

renderMessage : function( item ) {
    var messageView = new mssg.MessageView({
        model : item
    });
    this.$el.append( messageView.render().el );
}

});

this is the collection

这是集合

var mssg = mssg || {};

mssg.Messages = Backbone.Collection.extend({
    model : mssg.Message,
    url : 'messages'
});

and this is how it is initialized:

这是它的初始化方式:

var mssg = mssg || {};

$(function() {
    new mssg.MessagesView({
        collection : new mssg.Messages()
    });
});

The problem is that the renderfunction bound to resetdoesn't fire after the ajax fetch request.

问题是render绑定到的函数reset在 ajax 获取请求之后不会触发。

If I bind it to addit works. I tried binding allto a debuggin function and it says that the syncevent is called alongside the addfor every item.

如果我将它绑定到add它的工作。我尝试绑定all到调试函数,它说该sync事件与add每个项目一起调用。

回答by nikoshr

If you check backbone change log, you'll see that the way fetch is handled changed in 1.0:

如果您检查主干更改日志,您将看到 1.0 中处理 fetch 的方式发生了变化:

Renamed Collection's "update" to set, for parallelism with the similar model.set(), and contrast with reset. It's now the default updating mechanism after a fetch. If you'd like to continue using "reset", pass {reset: true}

将 Collection 的“更新”重命名为 set,与类似的 model.set() 并行,并与 reset 形成对比。它现在是获取后的默认更新机制。如果您想继续使用“重置”,请通过 {reset: true}

So, to trigger a reset event, you now have to use

因此,要触发重置事件,您现在必须使用

this.collection.fetch({reset: true})

回答by freestyle21

in backbone 1.0, you have to trigger reset by hand:

在主干 1.0 中,您必须手动触发重置:

youColloection.fetch({reset: true});