2013-08-18 74 views
4

我正在尝试向集合添加新模型(这次我没有保存到服务器,只是在内存中执行此操作)。我有下面的代码:将新模型添加到骨干集合,而不是替换

$(function() { 

//Model 

var Story = Backbone.Model.extend({ 

    defaults: { 
    'title': 'This is the title', 
    'description': 'Description', 
    'points': 0 
    }, 

    url: '/' 

}); 

//Collection 

var Stories = Backbone.Collection.extend({ 

    model: Story, 

    url: '/' 

}); 

//View 

var BaseView = Backbone.View.extend({ 

    el: $('#container'), 

    events: { 
    'click .inner': 'onClickInner' 
    }, 

    onClickInner: function() { 

    this.options.x++; 

    this.story.set({ 
     'title': 'This is my collection test ' + this.options.x, 
     'description' : 'this is the description' 

    }); 

    this.stories.add(this.story); 

    this.render(); 

    }, 

    initialize: function() { 

    this.stories = new Stories(); 
    this.story = new Story(); 

    }, 

    render: function(){ 

     console.log(this.stories); 

    } 

}); 

//Initialize App 

    var app = new BaseView({ 
    'x' : 0 
    }); 

}); 

我的问题是,每次“onClickInner”运行的,我想一个新的模型添加到集合。但是,在我的代码中,取代了集合中的现有模型。我如何添加新模型而不是替换?

谢谢你的时间。

回答

11

这是因为您更新当前模型而不是添加新的新模型。要解决它,你必须执行你的收藏add方法。此方法将传递的数据作为新模型添加到您的集合中:

this.stories.add({ 
    'title': 'This is my collection test ' + this.options.x, 
    'description' : 'this is the description' 
}); 
+0

这解决了问题,谢谢。我对模型上的'set'方法做了些什么感到困惑。我以为我正在创建一个模型的新实例并将其添加到集合中。 – CarbonDry

+0

等一下,如果我将上述数据传递到我的集合中,那么使用该模型有什么意义?这是否使模型完全多余,因为我已经在上面写了它? – CarbonDry

+0

如果您不打算使用该模型 - 您可以将其删除。 –