简体   繁体   English

Backbone Model里面的验证方法没被调用?

[英]validate method inside Backbone Model not being called?

Beginning to learn Backbone, trying to do some simple validation inside my Person Model but the validate method doesn't seem to be run when I set a new age. 开始学习Backbone,尝试在我的Person Model中进行一些简单的验证,但是当我设置一个新的年龄时,似乎没有运行validate方法。 Can anyone explain where i may be going wrong on this? 任何人都可以解释我可能在哪里出错吗? Don't want to move on with my learning until I get this right. 在我做对了之前,不要继续我的学习。

JS JS

var Person = Backbone.Model.extend({

    defaults: {
        name: 'John Doe',
        age: 30,
        occupation: 'working'
    },

    validate: function(attrs) {

        console.log(attrs);

        if ( attrs.age < 0 ) {
            return 'Age must be positive, stupid';
        }

        if ( ! attrs.name ) {
            return 'Every person must have a name, you fool.';
        }

    },

    work: function() {
        return this.get('name') + ' is working.';
    }

});

Currently I am just getting and setting values in the console, so: 目前我只是在控制台中获取并设置值,因此:

var person = new Person({
    name: 'Lady Madonna',
    age: 23
});

person.on('error', function(model, error){
    console.log(error);
});

When I set age to be a negative value the validate method doesn't take effect: 当我将age设置为负值时,validate方法不会生效:

person.set('age', -55);

Model validation changed in Backbone 0.9.10 : Backbone 0.9.10中的模型验证已更改

Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the {validate:true} option is passed. 模型验证现在仅在Model#save中默认强制执行,并且在构造或Model#set中不再默认强制执行,除非传递{validate:true}选项。

and note that 并注意到

Model validation now fires invalid event instead of error . 模型验证现在触发无效事件而不是错误

So your code should be written as 所以你的代码应该写成

var person = new Person({
    name: 'Lady Madonna',
    age: 23
});

person.on('invalid', function(model, error){
    console.log(error);
});

person.set('age', -55, {validate : true});

And a Fiddle http://jsfiddle.net/nikoshr/aUxdS/ 还有一个小提琴http://jsfiddle.net/nikoshr/aUxdS/

By default, validate() gets called before a call to save() method. 默认情况下,在调用save()方法之前调用validate() If you also want it to be called before set() , you should specify the { validate : true } option, for example: 如果您还希望在set()之前调用它,则应指定{validate:true}选项,例如:

person.set({ age : -55 }, { validate : true });

Here is an example I wrote a while back. 这是我前一段时间写的一个例子。 Hope it helps: 希望能帮助到你:

So lets say you have a model called Animal: 所以假设你有一个名为Animal的模型:

var Animal = Backbone.Model.extend({
    defaults:  {
        name: '',
        speech: ''
    },
    validate: function(attribs) {
        if(attribs.name === ''){
            return "Your animal does not have a name.";
        }
    },
    initialize: function() {
        console.log('New Animal creation');
        this.on("change:name", function() {
            console.log("Change captured");
        });
        this.on("error", function(model, error) {
            console.log(error);
        });
    }
});

So when somewhere in javascript you do this: 所以当你在javascript的某个地方你这样做:

var dog = new Animal();
dog.set('speech', 'kef');

You will receive the following message / error: 您将收到以下消息/错误:

"Your Animal does not have a name."

Now the validation will not be called when creating the new object 'dog'. 现在,在创建新对象'dog'时不会调用验证。 You really need to set it as wel using the dog.set(). 你真的需要使用dog.set()来设置它。

Otherwise it will not produce an error. 否则它不会产生错误。

By changing the value later on it might also not give this error. 通过稍后更改值,它可能也不会给出此错误。 (you really need to use set I guess). (你真的需要使用我猜的集合)。

However you can always check if the model is in Valid state like this: 但是,您始终可以检查模型是否处于有效状态,如下所示:

Model.isValid().

This will return a false when the Model is not valid. 当模型无效时,这将返回false。 So this: 所以这:

var dog = new Animal();
dog.isValid(); //would return a 'false' 

dog.set({
    'speech': 'kef',
    'name': 'fido'
});
dog.isValid(); //would return a 'true'

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM