为什么不验证火错误 - backbone.js

时间:2013-02-24 18:13:51

标签: javascript backbone.js

为什么不验证触发错误,因为“fred”应该使验证条件在设置时返回true?

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

2 个答案:

答案 0 :(得分:1)

您的validate()在保存时被调用,但在设置属性时则不会被调用,除非您明确告诉它这样做。来自docs

  

默认情况下,在保存之前调用validate,但也可以调用   在设置之前,如果传递了{validate:true}。

答案 1 :(得分:0)

试试这个:在initialize()中,将this.bind('error')更改为this.on('invalid') 'error'事件是在调用save()之后服务器上的失败。 'invalid'用于客户端的验证错误。最后,将{validate: true}添加为person.set()调用的第二个参数。 Backbone默认情况下不会验证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