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

t2a7ltrp  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(216)

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

ukqbszuj1#

使用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();
n3schb8v

n3schb8v2#

我试过使用collection.length函数,但它一直失败,但去基本的帮助:
要获得我推荐的第一个模型:

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

要获取Model集合中的最后一个Model,请执行以下操作:

var lastModel = Models.pop();
var lastModelId = lastModel .get("id");

相关问题