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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18298877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:22:54  来源:igfitidea点击:

Adding new models to a backbone collection, not replace

javascriptbackbone.jscollectionsmodel

提问by CarbonDry

I am trying to add new models to a collection (i'm not saving to the server this time, just doing this in memory). I have the code below:

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

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

});

My question is this, for each time 'onClickInner' runs, I want to add a new model to the collection. However, in my code it replacesthe existing model in the collection. How do I add new models and not replace?

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

Thanks for your time.

谢谢你的时间。

回答by Vitalii Petrychuk

It happens because you update current model instead of adding new new one. To fix it you have to just execute addmethod on your collection. This method adds passed data as a new model to your collection:

发生这种情况是因为您更新了当前模型而不是添加新模型。要修复它,您只需add在您的集合上执行方法。此方法将传递的数据作为新模型添加到您的集合中:

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