我刚刚开始使用backbone.js,我正在寻找一种在模型上声明字段而无需提供默认值的方法。它实际上仅供参考,以便当我开始创建实例时,我可以看到需要初始化哪些字段。
用java之类的东西我会写
public class CartLine{
StockItem stockItem;
int quantity;
public int getPrice(){
return stockItem.getPrice() * quantity;
}
public int getStockID(){
//
}
}
然而,对于骨干模型,我引用了我的方法中的字段,但我实际上并没有声明它们 - 看起来我可以轻松创建一个CartLine
不包含的对象stockItem
属性或quantity
属性。当我声明对象时不提及字段感觉很奇怪。特别是因为对象应该代表服务器上的实体。
var CartLine = Backbone.Model.extend({
getStockID: function(){
return this.stockItem.id;
},
getTotalPrice: function() {
return this.quantity * this.StockItem.get('price');
}
});
我想我可以通过使用 validate 添加某种参考 -
CartLine.validate = function(attrs){
if (!(attrs.stockItem instanceof StockItem)){
return "No Valid StockItem set";
}
if (typeof attrs.quantity !== 'number'){
return "No quantity set";
}
}
但我的问题是——我错过了什么吗?这有既定的模式吗?
The defaults
实际上是用于“字段”或作为 json 的一部分从服务器来回传输的数据。
如果您只想创建一些成员变量作为模型的一部分,这些变量是专有的并且不会来回发送到服务器,那么您可以 a) 在对象本身上或 b) 在初始化 http://backbonejs.org/#Model-constructor方法(在构造期间调用),它们可以作为 opts 的一部分传入:
var Widget = Backbone.Model.extend({
widgetCount: 0,
defaults: {
id: null,
name: null
}
initialize: function(attr, opts) {
// attr contains the "fields" set on the model
// opts contains anything passed in after attr
// so we can do things like this
if( opts && opts.widgetCount ) {
this.widgetCount = opts.widgetCount;
}
}
});
var widget = new Widget({name: 'the blue one'}, {widgetCount: 20});
请记住,如果您在类上声明对象或数组,它们本质上是常量,更改它们将修改所有实例:
var Widget = Backbone.Model.extend({
someOpts: { one: 1, two: 2},
initialize: function(attr, opts) {
// this is probably not going to do what you want because it will
// modify `someOpts` for all Widget instances.
this.someOpts.one = opts.one;
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)