Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

javascript - backbone collection fetch doesn't fire reset()

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 render function bound to reset doesn't fire after the ajax fetch request.

If I bind it to add it works. I tried binding all to a debuggin function and it says that the sync event is called alongside the add for every item.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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}

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...