2013-02-24 29 views
1

爲什麼不驗證激發錯誤,因爲「fred」應該使得驗證條件在設置時返回true?爲什麼不驗證激發錯誤 - backbone.js

Person = Backbone.Model.extend({ 

    initialize: function() { 
     console.log('inisialize Person'); 
     this.bind("change:name", function() { 
      console.log(this.get('name') + ' is now the name value') 

     }); 
     this.bind("error", function (model, error) { 

      console.log(error); 

     }); 
    }, 
    defaults: { 
     name: '', 
     height: '' 
    }, 
    validate: function (attributes, options) { 

     if (attributes.name == "fred") { //why wont this work? 

      return "oh no fred is not allowed"; 
     } 

    } 

}); 

//var person = new Person({ name: 'joe', height: '6 feet' }); 
var person = new Person(); 
person.set({ name: 'fred', height: '200' }); 

回答

1

你的validate()被調用保存時,但不能設置的屬性時,除非你明確告訴它這樣做。從docs

默認情況下驗證之前保存調用,但還可以設置前,如果{驗證:真}被稱爲 傳遞。

+0

謝謝 - 你知道嗎? – 2013-02-24 19:30:02

+0

謝謝 - 看起來我需要添加person.set({name:'fred',height:'200'},{validate:true}); – 2013-02-24 19:38:32

+0

並且必須將錯誤更改爲無效this.bind(「invalid」,function(model,error){ console.log(error); }); – 2013-02-24 19:44:40

0

試試這個:在initialize(),改變this.bind('error')this.on('invalid')'error'事件是故障的服務器,調用save時後()。 'invalid'用於客戶端的驗證錯誤。最後,將{validate: true}作爲第二個參數添加到person.set()調用中。骨幹默認不驗證set()

Person = Backbone.Model.extend({ 
    defaults: { 
     name: '', 
     height: '' 
    }, 

    validate: function(attributes) { 
     if(attributes.name === 'fred') 
     return 'oh no fred is not allowed'; 
    }, 

    initialize: function() { 
     alert('welcome'); 
     this.on('invalid', function(model, error){ 
      alert(error); 
     }); 
     //listeners 
     this.on('change:name', function(model) { 
      var name = model.get('name'); 
      alert('changed ' + name); 
     }); 

}); 

var person = new Person(); 
person.set({ name: 'fred', height: '200' }, {validate: true}); //oh no fred is not allowed