2016-02-18 21 views
1

当我通过传递{validate:true}使用unset()可以强制验证?在backbone.js当我通过传递{validate:true}使用unset()可以强制验证吗?

var Person = new Backbone.Model({ name: 'byer' }); 

Person.validate = function(attrs) { 

    if (!attrs.name) { 

    return 'I need your name'; 
    } 

}; 

Person.set({ name: 'byer' }); 
console.dir(Person.attributes); 

Person.unset('name'); 
console.dir(Person.attributes); 

Person.unset('name', { validate: true }); 
console.dir(Person.attributes); 

Person.unset('name', { validate: false }); 
console.dir(Person.attributes); 

传递{validate:ture}和{validate:false}有什么区别?

如果我没有传递任何选项,验证将是错误的?

回答

1

如果我没有传递任何选项,验证将是错误的?

是的。默认情况下Backbone不会执行验证。

下面是unset代码:

unset: function(attr, options) { 
    return this.set(attr, void 0, _.extend({}, options, {unset: true})); 
}, 

所以它只是set一个额外的标志unset。现在,基于此unset标志执行set/unset的代码位于执行验证的代码之后。如果通过验证标志({ validate: true })并且验证失败,则将不执行该操作,否则将执行该操作。

通过{ validate: false }而未通过验证标志具有相同的效果 - 该操作将在没有任何验证的情况下执行。

相关问题