Backbone.js - 自定义设置器
想象一个简单的骨干模型,就像
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
这样做的最佳方法是什么?这就是我能想到的:
- 覆盖“set”方法
- 使用“SantizedModel”来侦听此基本模型上的更改并存储清理后的输入。然后,所有视图代码都将传递给这个经过净化的模型。
我提到的特定“小写”示例在技术上可能在检索它时由视图更好地处理,但想象一下不同的情况,例如,用户输入以英镑为单位的值,而我只想将值以 $s 存储在我的数据库中。对于同一模型也可能有不同的视图,我不想在使用它的任何地方都必须执行“toLowerCase”。
想法?
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:
- Override the "set" method
- Use a "SantizedModel" which listens for changes on this base model and stores the sanitized inputs. All view code would then be passed this sanitized model instead.
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.
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
更新:您可以使用插件:https://github.com/berzniz/backbone .getters.setters
您可以像这样重写 set 方法(将其添加到您的模型中):
UPDATE: you can use the plug-in: https://github.com/berzniz/backbone.getters.setters
You can override the set method like this (add it to your models):
这将是一个黑客,因为这不是它的目的,但你总是可以为此使用验证器:
验证函数将被调用(只要
silent
选项不存在) set) 在模型中设置值之前,因此它让您有机会在数据真正设置之前改变数据。It would be a hack, because this isn't what it was made for, but you could always use a validator for this:
The validate function will get called (as long as the
silent
option isn't set) before the value is set in the model, so it gives you a chance to mutate the data before it gets really set.不是为了自吹自擂,而是我创建了一个具有“计算”属性的 Backbone 模型来解决这个问题这。换句话说,
您还监听计算属性的更改,并且几乎只是将其视为常规属性。
提到的插件 Bereznitskey 也是一种有效的方法。
Not to toot my own horn, but I created a Backbone model with "Computed" properties to get around this. In other words
You also listen for changes on computed properties and pretty much just treat this as a regular one.
The plugin Bereznitskey mentioned is also a valid approach.