【问题标题】:Adding new models to a backbone collection, not replace将新模型添加到主干集合中,而不是替换
【发布时间】:2013-08-20 08:51:21
【问题描述】:

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

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

感谢您的宝贵时间。

【问题讨论】:

    标签: javascript backbone.js collections model


    【解决方案1】:

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

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

    【讨论】:

    • 这解决了问题,谢谢。我对模型上的“设置”方法在做什么感到困惑。我以为我正在创建一个模型的新实例并将其添加到集合中。
    • 等一下,如果我将上述数据传递到我的集合中,那么使用模型有什么意义?它不会像我上面写的那样使模型完全冗余吗?
    • 如果您不打算使用该模型 - 您可以将其移除。
    • 我要使用模型
    • 如果您想拥有this.story 模型,我为您准备了演示jsfiddle.net/vpetrychuk/93cMM
    猜你喜欢
    • 2015-09-05
    • 2012-03-01
    • 2013-10-11
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多