1

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

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

2 回答 2

1

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

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

于 2013-02-24T18:21:09.883 回答
0

试试这个:在调用 save() 之后,将事件initialize()更改this.bind('error')为服务器失败。用于客户端的验证错误。最后,将作为第二个参数添加到调用中。Backbone 默认情况下不验证。this.on('invalid')'error''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
于 2014-09-19T23:14:13.310 回答