2012-02-01 61 views
0

我想一个新的虚拟领域添加到每当一个新的项目加入我的骨干模型,代码很简单:骨干示范场

window.DealModel = Backbone.Model.extend({ 
    defaults: { 
     title: '', 
     desc: '', 
     location: '', 
     terms: '', 
     price_orignial: 0, 
     price_discounted: 0 
    } 
}); 

window.DealCollection = Backbone.Collection.extend({ 
    model: DealModel, 

    initialize: function (models, options) { 
     this.bind('add', this.addTitleShort); 
    }, 

    addTitleShort: function(rdeal){ 
     rdeal.set('title_short', _.str.prune(rdeal.get('title') , 140, '+++')); 
    } 

}); 

不过,我不断收到一个_ Cannot use 'in' operator to search for 'id' in title_short_,不确定问题是什么,感谢帮助。

回答

0

我认为“set”使用对象哈希:

rdeal.set({ title_short: _.str.prune(rdeal.get('title') , 140, '+++') }); 

但是,如果没有“title_short”属性中创建的模型,我不知道你是否能“套”了。你可以做

rdeal.title_short = _.str.prune(rdeal.get('title') , 140, '+++'); 

你也可以添加一个功能模型类,将返回的结果,从而消除了需要处理模型的“change”事件:

window.DealModel = Backbone.Model.extend({ 
    ... 
    title_short: function() { 
     return _.str.prune(this.get('title') , 140, '+++'); 
    } 
}); 

,并使用它:myModelInstance.title_short();

希望它有帮助。