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;

last()Underscore JS の好意により、バックボーンが各コレクションでメソッドを提供することを追加するために編集されました(これを指摘してくれた@RocketRに感謝します)。したがって、上記は次のように簡単に記述できます。

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