2

所以我有一个页面,用户通过复选框从可用选项列表中进行选择。我有 3 个集合:一个用于可能的选项列表,一个用于当前保存的选项,以及一个已保存选项的克隆。当他们单击复选框时,我正在使用克隆列表添加/删除选项。

var possibleOptions = new Backbone.Collection("/options");   
var currentUserOptions = new Backbone.Collection("/useroptions", { id: 2 });
var clonedUserOptions = new Backbone.Collection(currentUserOptions.toJSON());

采用这种方法的原因是用户可以在编辑过程中取消选项页面,因此希望在单击保存按钮时选项保持不变。在选中/未选中选项时,将正确更新clonedoptions。但是,当我尝试更新真实列表时,似乎什么也没发生。

currentUserOptions.update(clonedUserOptions.toJSON());

我的期望是骨干网会根据文档(http://documentcloud.github.com/backbone/#Collection-update)触发对新模型的发布请求并删除每个缺失模型。如果我误解了这是如何工作的,请告诉我。一个正确方法的简单工作示例将不胜感激。

谢谢,CF

4

1 回答 1

0

据我了解,当集合发生变化时(正如人们所提到的),您必须使用单独的模型调用来更新服务器。有一些事件可以涵盖这些变化。但是,您可以使用同步发送整个集合。添加或删除每个模型时,您可以将其标记为新模型和已删除模型,并在准备好保存时发送整个集合。您的服务器方法必须在发送集合时确定适当的添加或删除操作。

这是进行批量同步的示例。而不是使用 this.collection.remove() 您可能只想像我提到的那样将其标记为已删除。这几乎是服务器知道要删除什么的唯一方法。从技术上讲,您可以删除所有内容,然后只添加在批量更新中发送的内容:) 此外,当您保存以更新实际已删除的内容时,您可能需要再次获取或从服务器返回一个集合。我不确定这对您的情况有帮助,但我已将它用于“完成后保存”一个按钮概念的页面。

    var one = new model({ id: this.collection.length + 1});
    var two = new model({ id: this.collection.length + 2 });
    var three = new model({ id: this.collection.length + 3 });
    var four = new model({ id: this.collection.length + 4 });
    var five = new model({ id: this.collection.length + 5 });


    this.collection.add(one.toJSON());
    this.collection.add(two.toJSON());
    this.collection.add(three.toJSON());
    this.collection.add(four.toJSON());
    this.collection.add(five.toJSON());

    this.collection.sync('update', this.collection, { success: function () {    console.log(this.collection.length); } });

    this.collection.remove(one);
    this.collection.remove(two);

    this.collection.sync('update', this.collection, { success: function () { console.log(this.collection.length); } });

在你的情况下:

currentUserOptions.sync('update', currentUserOptions, { success: function () { //do something } });
于 2013-03-22T16:04:55.340 回答