验证不起作用?

时间:2014-09-13 04:51:55

标签: backbone.js

我有一些代码:

       var Person = new Backbone.Model({name: 'Jeremy'});

        Person.validate = function(attrs) {
            if (!attrs.name) {
                return 'I need your name';
            }
        };

        Person.on("invalid", function(model, error) {
          alert(model.get("title") + " " + error);
        });


        Person.set({name: 'Samuel'});
        console.log(Person.get('name'));
        // 'Samuel'

        Person.unset('name', {validate: true});
        console.log(Person.get('name'));//Why can i print name here if it unsetted?

当我输入未设置的方法时,我会看到错误提示。这是对的。但是,为什么我可以在控制台中打印出未设置的名称?

2 个答案:

答案 0 :(得分:0)

name仍然存在,因为验证失败阻止unset做任何事情。

documentation对于验证如何与setunset一起使用并不十分明确,但save非常明确:

  

验证 model.validate(attributes, options)

     

[...]如果验证返回错误,save将无法继续,并且不会在服务器上修改模型属性。

因此,认为验证错误会阻止当前操作(setunsetsave,...)更改任何内容是合理的。

通过检查Backbone源代码,您可以了解它是如何工作的。首先,您需要知道unset只是伪装成set来电:

unset: function(attr, options) {
  return this.set(attr, void 0, _.extend({}, options, {unset: true}));
}

所以我们看一下set

set: function(key, val, options) {
  // A bunch of boring bookkeeping stuff...

  // Run validation.
  if (!this._validate(attrs, options)) return false;

  // The stuff that changes attributes and triggers events.
}

只要set知道它正在使用什么,就会发生验证,如果验证失败,set会返回而不会更改任何内容。

Backbone文档留下了很多重要的东西,所以如果你打算使用Backbone,你需要熟悉Backbone来源。来源相当直接,不要害怕跳进去看看发生了什么。

答案 1 :(得分:0)

执行此操作:要不触发事件,可以使用silent:true选项。我相信您的代码上游可能存在一些问题。无论如何,做以下 - 它应该工作。 (在我的测试中,确实如此)。

Person.unset('name',{validate: true,silent:true})

p.s。:Mu(下面)给出了很好的信息。

相关问题