1

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

2 に答える 2

1

あなたの validate() は保存時に呼び出されますが、明示的に指示しない限り、属性の設定時には呼び出されません。ドキュメントから:

デフォルトでは、validate は保存前に呼び出されますが、{validate:true} が渡された場合は設定前に呼び出すこともできます。

于 2013-02-24T18:21:09.883 に答える
0

これを試してみてください: でinitialize()、 を に変更this.bind('error')this.on('invalid')ます'error'。は'invalid'、クライアント側の検証エラー用です。{validate: true}最後に、2 番目の引数として呼び出しに追加し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 に答える