2013-03-25 86 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' 

希望這有助於!