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”运行的,我想一个新的模型添加到集合。但是,在我的代码中,取代了集合中的现有模型。我如何添加新模型而不是替换?
谢谢你的时间。
这解决了问题,谢谢。我对模型上的'set'方法做了些什么感到困惑。我以为我正在创建一个模型的新实例并将其添加到集合中。 – CarbonDry
等一下,如果我将上述数据传递到我的集合中,那么使用该模型有什么意义?这是否使模型完全多余,因为我已经在上面写了它? – CarbonDry
如果您不打算使用该模型 - 您可以将其删除。 –