在主干模型上声明变量而不设置默认值

Declaring variables on a backbone model without setting defaults

本文关键字:设置 默认值 变量 声明 模型      更新时间:2023-09-26

我刚开始使用backbone.js,我正在寻找一种在模型上声明字段而无需提供默认值的方法。它实际上只是供参考,这样当我开始创建实例时,我就可以看到我需要初始化哪些字段。

在java中,我会写

public class CartLine{
    StockItem stockItem;
    int quantity;
    public int getPrice(){
        return stockItem.getPrice() * quantity;
    }
    public int getStockID(){
        //
    }
}

然而,骨干模型,我引用我的方法中的字段,但我实际上并没有声明它们-看起来我可以很容易地创建一个不包含stockItem属性或quantity属性的CartLine对象。当我声明对象时不提及字段感觉很奇怪。特别是当对象应该代表服务器上的实体时。

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";
  }
}

但我的问题是——我错过了什么吗?这有固定的模式吗?

defaults实际上是用于作为json的一部分从服务器来回传输的"字段"或数据。

如果你只是想创建一些成员变量作为模型的一部分,这些成员变量是私有的,不会被来回发送到服务器,那么你可以a)在对象本身或b)在初始化方法(在构造期间调用)中声明它们,它们可以作为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; 
    }
});