3

我有一个基本的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();
4

2 回答 2

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);

您的render()函数将如下所示:

render: function(){
    var last_model = this.collection.at(this.collection.length - 1);
    this.renderThing(last_model);
}

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

var total = this.collection.length;

编辑添加 Backbone 为last()每个集合提供了一个方法,由 Underscore JS 提供(感谢@RocketR指出这一点)。因此,上面可以更容易地写成如下:

var last_model = this.collection.last();
于 2012-07-19T19:09:42.827 回答
1

我曾尝试使用该collection.length功能,但一直失败,但了解基础知识有所帮助:

要获得我推荐的第一个模型:

var firstModel = Models.at(0);      
alert(firstModel.get("attribute"));

要获取模型集合中的最后一个模型:

var lastModel = Models.pop();
var lastModelId = lastModel .get("id");
于 2017-06-13T14:09:46.810 回答