在骨干收藏中看不到我的模特

时间:2012-10-30 18:45:53

标签: javascript collections backbone.js model

我正在尝试将一个项目添加到集合中,但首先我要删除现有项目。只有一个项目存在。我可以创建一个新的,只是不删除一个。也许我正在倒退。

这是我的集合,changetheme是被调用的函数,它可以解决,但无法弄清楚如何删除现有函数。 this.model.destroy()只会抛出一个错误。也许我已脱离了背景。

bb.model.Settings = Backbone.Collection.extend(_.extend({
    model:  bb.model.Setting,
    localStorage: new Store("rrr"),

    initialize: function() {
        var self = this
        this.model.bind('add', this.added, this);
    },
    changetheme: function(value) {
        var self = this
        this.destroy();
        this.create({theme:value});
    },
}));

如果重要,那就是我的模特

bb.model.Setting = Backbone.Model.extend(_.extend({
    defaults: {
        theme: 'e'
    },
    initialize: function() {
        var self = this;
    },
    added: function(item) {
        var self = this;
        this.destroy(); 
    },
}));

1 个答案:

答案 0 :(得分:1)

要从集合中删除第一项,您可以拨打collection.shift(),也可以通过拨打collection.reset()清除收藏。所以在你的情况下,可以写:

changetheme: function(value) {
    this.shift();
    this.create({theme:value});
}

<强> UPD 好的,让我解释一下 - 在你的例子中,localStorage和其他服务器端一样。因此,当您调用“创建”时,根据docs骨干实例化具有属性哈希的模型,将其保存到服务器(localStorage),并在成功后添加到集合中创建。这就是为什么您的收集项目计数增加每页刷新。但是,当您调用 shift / remove docs时,只会影响客户端集合,而不会影响服务器(localStorage)。现在,从服务器和客户端删除模型的最佳选择是调用模型的destroy方法:

changetheme: function(value) {
    var modelToDelete = this.at(0) //take first model
    modelToDelete.destroy();
    this.create({theme:value});
}