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

标签 javascript backbone.js collections model

我正在尝试将新模型添加到集合中(这次我没有保存到服务器,只是在内存中这样做)。我有以下代码:

$(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”运行时,我都想向集合中添加一个新模型。但是,在我的代码中,它替换 集合中的现有模型。如何添加新模型而不是替换?

感谢您的宝贵时间。

最佳答案

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

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

关于javascript - 将新模型添加到 Backbone 集合中,而不是替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298877/

相关文章:

javascript - 带有 Backbone.js 的 JS 模板系统

java - containsKey HashMap<> 的实现 - Java

javascript - 计算数组中的空值

php - 如何在 JavaScript 中包含链接+id

javascript - ECMAScript 2015(ECMAScript 6) 有类初始值设定项吗?

javascript - array.filter 参数仅在包裹在 {} 周围时才有效

backbone.js - 创建新的 Backbone View 时如何知道元素是否已经在 DOM 中

events - keyup 事件未触发 - 主干

java - Apache CollectionUtils 的良好用途

kotlin - 阻塞每个方法的同步集合