【问题标题】:Updating a model in a collection更新集合中的模型
【发布时间】:2012-01-21 15:06:41
【问题描述】:

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

        }

感谢您的帮助

【问题讨论】:

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


    【解决方案1】:

    我同意 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 事件将触发并触发与您的模型及其集合的任何绑定

    希望对你有帮助:)

    【讨论】:

      【解决方案2】:

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

      这是一个例子。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        • 1970-01-01
        相关资源
        最近更新 更多