将新模型添加到主干集合中,而不是替换

Car*_*Dry 4 javascript collections model backbone.js

我正在尝试将新模型添加到集合中(这次我没有保存到服务器,只是在内存中执行此操作).我有以下代码:

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

});
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的时间.

Vit*_*huk 11

这是因为您更新当前模型而不是添加新的模型.要修复它,你必须只add对你的集合执行方法.此方法将传递的数据作为新模型添加到您的集合中:

this.stories.add({
  'title': 'This is my collection test ' + this.options.x,
  'description' : 'this is the description'
});
Run Code Online (Sandbox Code Playgroud)