骨干收集始终与n个模型

时间:2013-05-07 00:28:07

标签: backbone.js backbone-events

我正在尝试列出最近十个或更少的模型列表。我有事件用create动态添加模型。这个事件在集合上调用'add',并且我的逻辑正确地添加了一个元素。但我需要添加新元素,检查集合是否超过10,如果它是真的删除最后一个模型并添加新的

var model = Backbone.Model.extend({
  defaults: function() {
    return {id:null}
  }
});

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

var view = Backbone.View.extend({
   initialize: function(){
    var self = this;
    this.listenTo(collection, 'add', this.addOne);
    this.listenTo(collection, 'reset', this.addAll);
    this.listenTo(collection, 'all', this.render);
   },
   render: function(){
    this.$el.html();
return this;
   },
   addAll: function(){
this.collection.each(this.addOne, this);
   },
   addOne: function(model){
    //this is executed after 'create' but before this I need slice my collection
var view = new view({model:model});
this.$el.prepend(view.render().el);
   }
});

感谢

2 个答案:

答案 0 :(得分:3)

在您initialize的{​​{1}}事件的Backbone.Collection.extend中绑定一个功能,以检查您的尺寸。

add

答案 1 :(得分:1)

你可以这样做:

   addOne: function(model){
      //this is executed after 'create' but before this I need slice my collection
      if !model.get('new_field')
         model.set({new_field, ""})
      newField = new Date();
      while (this.collection.findWhere({new_field:newField})){
         newField = new Date();
      }
      model.set({new_field, newField});
      var view = new view({model:model});
      this.$el.prepend(view.render().el);
      this.checkLength()
   },
   checkLength: function(){
      if (this.collection.length > 10) {
          // remove model which gets minimum value by 'new_field'
      }
   }