Backbone.js - fetch method does not fire reset eve

2019-02-05 05:51发布

I'm beginning with Backbone.js and trying to build my first sample app - shopping list.

My problem is when I fetch collection of items, reset event isn't probably fired, so my render method isn't called.

Model:

Item = Backbone.Model.extend({
  urlRoot : '/api/items',
  defaults : {
    id : null,
    title : null,
    quantity : 0,
    quantityType : null,
    enabled : true
  }
});

Collection:

ShoppingList = Backbone.Collection.extend({
  model : Item,
  url : '/api/items'
});

List view:

ShoppingListView = Backbone.View.extend({

el : jQuery('#shopping-list'),

initialize : function () {
    this.listenTo(this.model, 'reset', this.render);
},

render : function (event) {
    // console.log('THIS IS NEVER EXECUTED');
    var self = this;
    _.each(this.model.models, function (item) {
        var itemView = new ShoppingListItemView({
            model : item
        });
        jQuery(self.el).append(itemView.render().el);
    });
    return this;
}

});

List item view:

ShoppingListItemView = Backbone.View.extend({

tagName : 'li',

template : _.template(jQuery('#shopping-list-item').html()), // set template for item

render : function (event) {
    jQuery(this.el).html(this.template(this.model.toJSON()));
    return this;
}

});

Router:

var AppRouter = Backbone.Router.extend({

routes : {
    '' : 'show'
},

show : function () {
    this.shoppingList = new ShoppingList();
    this.shoppingListView = new ShoppingListView({
        model : this.shoppingList
    });
    this.shoppingList.fetch(); // fetch collection from server
}

});

Application start:

var app = new AppRouter();
Backbone.history.start();

After page load, collection of items is correctly fetched from server but render method of ShoppingListView is never called. What I am doing wrong?

2条回答
smile是对你的礼貌
2楼-- · 2019-02-05 05:55

Are you using Backbone 1.0? If not, ignore this, otherwise, you may find what the doc says about the Collection#fetch method interesting.

To quote the changelog:

"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 basically, you're not making a reset here but an update, therefore no reset event is fired.

查看更多
一纸荒年 Trace。
3楼-- · 2019-02-05 05:59

Here's your problem:

" When the model data returns from the server, it uses set to (intelligently) merge the fetched models, unless you pass {reset: true}" Backbone Docs

So, you want to fire the fetch with the reset option:

this.shoppingList.fetch({reset:true}); // fetch collection from server

As an aside, you can define a collection attribute on a view:

this.shoppingList = new ShoppingList();
  this.shoppingListView = new ShoppingListView({
     collection : this.shoppingList  // instead of model: this.shoppingList
  });
查看更多
登录 后发表回答