Backbone.js:仅渲染集合中的最后一个模型,显示模型的总数

use*_*779 3 javascript backbone.js

我有一个基本的backbone.js应用程序,它呈现了一组模型.我想修改为仅渲染最后一个模型,并显示模型总数的数字.到目前为止,这是我的代码:

 var Thing = Backbone.Model.extend({
 });

 var ThingView = Backbone.View.extend({
    el: $('body'),
     template: _.template('<h3><%= title %></h3>'),

     render: function(){
         var attributes = this.model.toJSON();
         this.$el.append(this.template(attributes));
     }
 });


 var ThingsList = Backbone.Collection.extend({
   model: Thing
});

var things = [
  { title: "Macbook Air", price: 799 },
  { title: "Macbook Pro", price: 999 },
  { title: "The new iPad", price: 399 },
  { title: "Magic Mouse", price: 50 },
  { title: "Cinema Display", price: 799 }
];

var thingsList = new ThingsList(things);


var ThingsListView = Backbone.View.extend({
   el: $('body'),
   render: function(){
     _.each(this.collection.models, function (things) {
            this.renderThing(things);
        }, this);
    },


  renderThing: function(things) {
    var thingView = new ThingView({ model: things }); 
    this.$el.append(thingView.render()); 
  }

});

var thingsListView = new ThingsListView( {collection: thingsList} );
thingsListView.render();
Run Code Online (Sandbox Code Playgroud)

Col*_*ock 13

使用at()以下方法从集合中获取最新模型:

// this.collection.length - 1 is the index of the last model in the collection
var last_model = this.collection.at(this.collection.length - 1);
Run Code Online (Sandbox Code Playgroud)

你的render()功能看起来像这样:

render: function(){
    var last_model = this.collection.at(this.collection.length - 1);
    this.renderThing(last_model);
}
Run Code Online (Sandbox Code Playgroud)

使用length属性获取集合中的模型总数:

var total = this.collection.length;
Run Code Online (Sandbox Code Playgroud)

编辑补充说,Backbone为last()每个集合提供了一个方法,由Underscore JS提供(感谢@RocketR指出这一点).所以,上面的内容可以更容易地写成如下:

var last_model = this.collection.last();
Run Code Online (Sandbox Code Playgroud)

  • Collection有一个`last`方法来获取最后一个元素. (14认同)