更新集合中的模型

时间:2011-12-15 23:54:55

标签: jquery backbone.js javascript-framework backbone-events

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

        }

感谢您的帮助

2 个答案:

答案 0 :(得分: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();
});

答案 1 :(得分:0)

我同意Paul的观点,你应该有一个View for your collection,以及一个View for your model。 模型的视图允许您编辑模型,并且保存应该正确传播。

然而,说你似乎有一个视图,有1个模型和1个集合(基于你的删除并添加this.model)所以你有一个显示单个模型的视图...我假设:D < / p>

然后你可以这样做。

    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事件将触发并触发任何绑定到你的模型的集合

希望有所帮助:)

相关问题