1

我的问题是如何更新集合中的模型?这就是我正在做的事情。在页面加载时,我获取联系人列表。在一个视图中,我在一个无序列表中列出了这些联系人。每个联系人都是可点击的,这将带您进入编辑表单。对联系人进行更改后,您可以保存该联系人。这将带您进入将更改的模型保存回集合的方法。你会怎么做?在骨干文档中没有更新方法(或者至少我没有看到它)。我创建了一种方法来做到这一点,但我不确定它是否是首选的 Backbone 方式。这里是:

        updatePlan : function()
        {
            //unique ID of the model
            var id = $( 'input[ name=id ]' ).val();
            //remove the old model from the collection
            this.collection.remove( this.model );
            //add the updated model to the collection
            this.collection.add( this.model );              

        }

你会认为会有这样的功能:

        updatePlan : function()
        {
            this.collection.update( this.model );

        }

谢谢您的帮助

4

2 回答 2

0

您可以让您的视图允许用户编辑联系人为您更新模型。而且由于模型是通过引用传递的,它也将在它所属的集合中更新。

这是一个例子。

EditView = Backbone.View.extend({
  events: {
    'change #name': 'nameChanged',
    'change #age': 'ageChanged'
  },
  render: function() {
    //render code
  },
  nameChanged: function() {
    var nameValue = this.$('#name').val();
    this.model.set({ Name : nameValue });
  },
  ageChanged: function() {
    var ageValue = this.$('#age').val();
    this.model.set({ Age : ageValue });
  }
}

然后在创建编辑视图时,从集合中传入选定的模型

selectedContact = contactCollection.at(0);
var editView = new EditView({ model: contact });
$('#editDiv').html(editView.render().el);

剩下要做的就是在用户单击保存按钮时将模型保存到服务器。

$('#saveButton').click(function() {
  selectedContact.save();
});
于 2011-12-16T01:02:37.113 回答
0

我同意 Paul 的观点,您应该为您的收藏提供一个视图,并为您的模型提供一个视图。模型的视图允许您编辑模型,并且保存应该正确传播。

但是,这表示您似乎在那里有一个视图,其中有 1 个模型和 1 个集合(基于您的删除和添加 this.model),因此您有一个显示单个模型的视图......我假设:D

然后你可以这样做。

    updatePlan : function()
    {
        //unique ID of the model
        var id = $( 'input[ name=id ]' ).val();
        this.model.set({id: id});
        this.model.save();
    }

我认为问题可能只是您最初的“逻辑”,您不会在集合中编辑模型。您编辑一个模型,该模型恰好属于一个集合。因此,模型和 model.collection 都会触发事件,就像在您的 id 集上一样,Change:id 事件将触发并触发与您的模型及其集合的任何绑定

希望能帮助到你 :)

于 2012-01-16T12:43:07.053 回答