自定义设置

Backbone.js - custom setters

本文关键字:设置 自定义      更新时间:2023-09-26

想象一个简单的骨干模型,如

window.model= Backbone.Model.extend({
   defaults:{
      name: "",
      date: new Date().valueOf()
   }
})

我试图找到一种方法,始终使模型存储在小写的名称,无论输入提供。例如,

model.set({name: "AbCd"})
model.get("name") // prints "AbCd" = current behavior
model.get("name") // print "abcd" = required behavior

做这件事的最好方法是什么?以下是我能想到的:

  1. 覆盖"set"方法
  2. 使用"SantizedModel"来监听这个基本模型上的更改,并存储经过处理的输入。然后,所有视图代码都将传递给这个经过处理的模型。

我提到的特定的"to lower case"示例在技术上可能由视图在检索时更好地处理,但是想象一下另一种情况,例如,用户以英镑输入值,而我只想在数据库中以$s存储值。同样的模型也可能有不同的视图,我不想在它被使用的地方做一个"toLowerCase"。

想法吗?

UPDATE:可以使用插件:https://github.com/berzniz/backbone.getters.setters


你可以像这样重写set方法(将它添加到你的模型中):

set: function(key, value, options) {
    // Normalize the key-value into an object
    if (_.isObject(key) || key == null) {
        attrs = key;
        options = value;
    } else {
        attrs = {};
        attrs[key] = value;
    }
    // Go over all the set attributes and make your changes
    for (attr in attrs) {
        if (attr == 'name') {
            attrs['name'] = attrs['name'].toLowerCase();
        }
    }
    return Backbone.Model.prototype.set.call(this, attrs, options);
}

这将是一个hack,因为这不是它的目的,但您总是可以使用验证器:

window.model= Backbone.Model.extend({
   validate: function(attrs) {
      if(attrs.name) {
         attrs.name = attrs.name.toLowerCase()
      }
      return true;
   }
})

在模型中设置值之前将调用validate函数(只要没有设置silent选项),因此它给了您在真正设置数据之前更改数据的机会。

不是我自己吹嘘,而是我创建了一个带有"Computed"属性的Backbone模型来解决这个问题。换句话说

var bm = Backbone.Model.extend({
  defaults: {
     fullName: function(){return this.firstName + " " + this.lastName},
     lowerCaseName: function(){
        //Should probably belong in the view
        return this.firstName.toLowerCase();  
     }
   }
})

您还可以侦听计算属性的更改,并且基本上只是将其视为常规更改。

Bereznitskey提到的插件也是一个有效的方法。