为什么不验证会触发错误,因为“ 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' });

最佳答案

保存时会调用validate(),但设置属性时不会调用它,除非您明确指示要这样做。从docs


  默认情况下,validate在保存之前被调用,但是也可以被调用
  如果已通过{validate:true},则在设置之前。

10-04 21:51
查看更多