【问题标题】:Fundamental issue with backbone collections骨干收藏的基本问题
【发布时间】:2012-10-18 23:52:51
【问题描述】:

试图让我的头脑绕过 Backbone,并且工作得很好,直到我遇到了下面的障碍,这让我觉得我做错了。

在下面的代码中,我有一个模型和一个集合。该集合称为bb.model.Settings 一个名为changetheme 的函数,它获取一个值。现在我有这么远的价值,但是当我去保存这个项目时,我需要将它传递给模型吗?我正在尝试调用模型中的保存函数,但我想知道我是否真的需要这个,它总是失败。我应该只保存收藏还是最好的方法来保存它

bb.model.Setting = Backbone.Model.extend(_.extend({    
    defaults: {
        theme: 'e'
    },

    initialize: function() {
        var self = this
        _.bindAll(self)
    },
    save: function() {
        var self = this
        _.bindAll(self)
    },
}))


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

    initialize: function() {
        var self = this
        _.bindAll(self)
    },
    changetheme: function(value) {
        var self = this
        _.bindAll(self)
        this.remove
        this.model.save() 
    },
}))

【问题讨论】:

  • 分号在 JavaScript 中大部分是可选的,但将它们排除在外是一个坏习惯。
  • 好的,以后会加分号。
  • 关于如何保存我的项目的任何想法......似乎没有任何工作。
  • 我是这样做的,它有效,但可能不是最好的方法 changetheme: function(value) { var self = this _.bindAll(self) var item = new bb.model.Item( { 主题:值 }) self.add(item) item.save() },

标签: javascript collections backbone.js models


【解决方案1】:

尝试检查一下这个小提琴,你的代码中有几个错误:

http://jsfiddle.net/8gDqb/1/

这是 js 部分,完整的工作示例请参见小提琴:

var bb = {};
bb.model={};

bb.model.Setting = Backbone.Model.extend({    
    defaults: {
        theme: 'e'
    },

    initialize: function() {
        var self = this
        //_.bindAll(self) // no longer necessary with backbone.js
    },
    save: function() {
        var self = this
        //_.bindAll(self) // no longer necessary with backbone.js
    },
});


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

    initialize: function() {
        var self = this
        //_.bindAll(self) // no longer necessary with backbone.js
    },
    changetheme: function(value) {
        var self = this
        _.bindAll(self)
        //this.remove
        //_.bindAll(self) // no longer necessary with backbone.js
    },
});

此外,以防万一您正在阅读有关网络骨干网的旧操作指南,您不再需要 bindAll。这已经有一段时间没有必要了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 2015-12-13
    • 2016-03-31
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    相关资源
    最近更新 更多