backbone.js - 从localStorage恢复后没有模型继承

时间:2012-03-02 17:07:58

标签: inheritance collections model backbone.js local-storage

从localStorage重写我的集合后,不再调用覆盖的方法(以下示例中为getLabel())。而是调用基本方法。我认为问题是,我告诉集合使用BaseModel。但是如何更改集合以使用模型KeywordLog和CommentLog?

我使用以下模型继承:

var BaseLog = Backbone.Model.extend({   
    defaults: {
        timecode: null,
        color: null,
        isRange: false,
    },  
    getLabel: function() {
        return 'base';
    }
});

var KeywordLog = BaseLog.extend({   
    defaults: _.extend({}, BaseLog.prototype.defaults, {
        keyword: null,      
    }),     
    getLabel: function() {
        return 'keyword';
    }
});

var CommentLog = BaseLog.extend({   
    defaults: _.extend({}, BaseLog.prototype.defaults, {
        text: null,     
    }), 
    getLabel: function() {
        return 'comment';
    }
});

var Loglist = Backbone.Collection.extend({
    // This might be the problem after restoring drom localStorage..? 
    model: BaseLog,
    localStorage: new Store("storage")
});     

1 个答案:

答案 0 :(得分:0)

集合仅适用于单一模型类型。我建议您切换到单个模型,并将label作为属性。

var Log = Backbone.Model.extend({   
    defaults: {
        timecode: null,
        color: null,
        isRange: false,
        label: 'base',
        text: null
    },
    initialize: function() {
      _.bindAll(this);
    },
    getLabel: function() {
        return this.label;
    }
});

log = new Log;
log.set({ text: 'keyword here', label: 'keyword' })
log2 = new Log;
log2.set({ text: 'comment here', label: 'comment' })