2013-05-07 128 views
0

我试图用集合上最后十个模型或更少的模型做一个列表。我有事件来动态添加创建模型。这个事件在集合上调用'add',并用我的逻辑添加正确的一个元素。但我需要添加新的元素,检查是否收藏有超过10,如果这是真的删除最后一个模型,并添加新的骨干集合总是与n模型

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

感谢

回答

1

Yoou可以做这样的:

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' 
     } 
    } 
3

绑定Backbone.Collection.extendinitializeadd事件中的一个函数,其中您正在检查大小。

initialize: function() {    
    this.on('add', function() { 
     this.checkSize(); 
    }); 
}, 

checkSize: function() { 
    var max = 10; 

    if (this.length > max) { 
     this.reset(this.first(max)); 
    } 
}