Backbone.js的 - 自定义的制定者 [英] Backbone.js - custom setters
问题描述
想象一下,一个简单的模型骨干像
Imagine a simple backbone model like
window.model= Backbone.Model.extend({
defaults:{
name: "",
date: new Date().valueOf()
}
})
我试图找到一种方法,始终使模型店提供了小写的名字,不论输入。即,
I'm trying to find a way to always make the model store the name in lower-case irrespective of input provided. i.e.,
model.set({name: "AbCd"})
model.get("name") // prints "AbCd" = current behavior
model.get("name") // print "abcd" = required behavior
什么是这样做的最佳方式?这里是所有我能想到的:
What's the best way of doing this? Here's all I could think of:
- 覆盖set的方法
- 使用一个SantizedModel,它监听在此基础上模式的变化和存储消毒的投入。然后,所有视图code将通过这种消毒模式来代替。
具体小写我提到可能在技术上被认为能更好地处理,例如在获取它,但是想象一下,在这里,比方说,用户在磅输入值不同的情况下,我只想要存储在$ S值我的数据库。也有可能是同一型号不同的看法,我不希望有的确无处不在其使用了与toLowerCase。
The specific "to lower case" example I mentioned may technically be better handled by the view while retrieving it, but imagine a different case where, say, user enters values in Pounds and I only want to store values in $s in my database. There may also be different views for the same model and I don't want to have to do a "toLowerCase" everywhere its being used.
思考?
推荐答案
更新:您可以使用插件:<一href=\"https://github.com/berzniz/backbone.getters.setters\">https://github.com/berzniz/backbone.getters.setters
您可以覆盖set方法如下(将它添加到您的模型):
You can override the set method like this (add it to your models):
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);
}
这篇关于Backbone.js的 - 自定义的制定者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!