2013-03-25 57 views
3

开始学习Backbone,试图在我的Person模型中进行一些简单的验证,但验证方法似乎没有在设置新时代时运行。任何人都可以解释我可能会出错吗?我不想继续学习,直到我明白为止。骨干模型里面的验证方法没有被调用?

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.'; 
    } 

}); 

目前,我刚开始并在控制台中设置的值,因此:

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

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

当我设置的年龄为负值的validate方法不生效:

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

你在哪里调用这些函数?你怎么打电话给他们? – 2013-03-25 12:24:52

+0

请添加如何设置新值的示例。 – mirrormx 2013-03-25 12:26:01

+0

增加了一个例子 – styler 2013-03-25 12:27:29

回答

10

模型验证changed in 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 validation now fires invalid event instead of error.

所以你的代码应该写成

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

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

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

并有小提琴http://jsfiddle.net/nikoshr/aUxdS/

+0

这仍然将年龄设置为-55虽然? – styler 2013-03-25 12:38:05

+0

@styler不,如果验证失败,则不设置属性。 http://jsfiddle.net/nikoshr/aUxdS/2/例如 – nikoshr 2013-03-25 12:39:53

+0

啊好吧,所以默认值被保护,但新的人物对象的年龄仍然会被设置是啊? – styler 2013-03-25 12:49:55

3

默认情况下,在调用save()方法之前调用。如果你也希望它set()之前被调用,您应该指定{验证:真}选项,例如:

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

+1验证示例.. – rahmat 2013-06-28 15:44:40

0

这里是我写的,而回的例子。 希望它能帮助:

因此,可以说你有一个叫做动物模型:

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); 
     }); 
    } 
}); 

所以,当某个地方在JavaScript你这样做:

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

您会收到以下消息/错误:

"Your Animal does not have a name." 

现在验证不会在crea时被调用给新对象'狗'。 你真的需要使用dog.set()来设置它。

否则它不会产生错误。

通过稍后更改值也可能不会产生此错误。 (你真的需要使用set我猜)。

但是你可以随时检查模型是有效的状态是这样的:

Model.isValid(). 

这将返回一个错误,当模型是无效的。 所以这个:

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

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

希望这有助于!