对一个实例进行设置时,在骨干模型验证只是做? [英] Is Validation on Models in Backbone only done when set on an instance?
问题描述
我已经创建了一个对象:
I have created an object:
var Person = Backbone.Model.extend({
defaults: {
'name': '',
'age': 0
},
initialize: function() {
this.on('error', function(model, error){
console.log(error);
});
},
validate: function(attributes){
if (attributes.name == '') {
return "How do we call him!?";
}
},
changeName: function(name) {
this.set({'name':name});
},
getOlder: function() {
this.set({'age': this.get('age') +1});
}
});
我创建一个Person的实例,并把一个空白的名字,我从来没有收到一个错误。但是,当我在一个已经创建的实例设置一个空白的名字,它打响了验证。
I create an instance of Person and put in a blank on the name and I never received an error. But when I set a blank name on an already created instance, it fired the validation.
var teejay = new Person;
teejay.changeName('');
=> How do we call him!?
teejay.get('name');
=> ""
这是什么,我从骨干源$ C $ C看到,我看到
From what I am seeing from the Backbone source code, I see
this.set(attributes, {silent: true});
是正确的假设,验证只是做每当属性被更改或设置?
Is it right to assume that validation is only done whenever attributes are changed or set?
推荐答案
骨干总是会调用验证
当 set方法
或保存
与当你在一个哈希传递给构造函数或例外的属性时,该模型实例化默认
的哈希值。
Backbone will always call the validate
method when you set
or save
an attribute with the exception of when you pass in a hash to the constructor or when the model instantiates with the default
hash.
例如
var myperson = new Person({name: ''});
不会调用验证
,因为构造方法必须返回该模型的新实例。
Will NOT call the validate
method since the constructor MUST return a new instance of the model.
然而,
var myperson = new Person();
myperson.set('name', '');
威尔。
您验证
方法永远不会打印出任何东西 - 在收益
上的验证用于测试是否不有效。如果返回任何东西truthy验证将失败,但仅此而已。这是由你来触发你想要的'错误'
消息或者其他。
Your validate
method will never print out anything -- the return
on validate is used to test whether or not it worked. If you return anything "truthy" validation will fail, but that's it. It's up to you to trigger the 'error'
message or whatever else you want.
你看到的是完全一样的,应预期。
What you're seeing is exactly as should be expected.
TL; DR:
你的默认
散永远不会被验证,因为它必须返回一个有效的模式。
TL;DR:
Your defaults
hash will not ever be validated since it has to return a valid model.
(同样,请允许我抬价我 Backbone.Validator 项目现在 - 唐未写你自己的!)
(Also, allow me to shill for my Backbone.Validator project now -- don't write your own!)
这篇关于对一个实例进行设置时,在骨干模型验证只是做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!