`
XUST
  • 浏览: 4454 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

Backbone 1.0.0 版 API _ Backbone.Model validate 解析

阅读更多

        最近一段时间在学习backbone,发现网上的很多资料都是旧版本的,有一些儿不适用于backbone1.0.0的最新版,尤其validate这个方法的用法。

        最老的旧版中,说的是:调用model的set方法会默认调用model的validate方法;稍微旧的版本中,说到调用model的set方法,传入{silent: true},可以启动validate校验,调用save方法会强制进行校验;在1.0.0的版本中,我们来看下官网的explain:

validatemodel.validate(attributes, options) 
This method is left undefined, and you're encouraged to override it with your custom validation logic, if you have any that can be performed in JavaScript. By defaultvalidate is called before save, but can also be called before set if {validate:true}is passed. The validate method is passed the model attributes, as well as the options from set or save. If the attributes are valid, don't return anything from validate; if they are invalid, return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically. If validate returns an error, save will not continue, and the model attributes will not be modified on the server. Failed validations trigger an "invalid"event, and set the validationError property on the model with the value returned by this method.

 

        validate方法在Backbone.Model中留下来,在继承Model的时候重写(自定义)validate方法。调用save方法前默认会调用validate方法,当然调用set方法,如果传入{validate: true}也可以调用validate方法。

        如果向model添加的attribute通过校验,validate不会返回任何值,如果没有通过校验(invalid),会返回你在validate方法中定义的错误。校验失败,会触发invalid事件,并且填充model的validateErro属性值。

 

var Chapter = Backbone.Model.extend({
  validate: function(attrs, options) {
    if (attrs.end < attrs.start) {
      return "can't end before it starts";
    }
  }
});

var one = new Chapter({
  title : "Chapter One: The Beginning"
});

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

one.save({
  start: 15,
  end:   10
});

 

如果你在chrome下跑个demo,你会发现save方法如果不传入{validate: true},即使验证不通过,one.toJSON()会发现start和end的值还是改变了

 

var Chapter = Backbone.Model.extend({
  validate: function(attrs, options) {
    if (attrs.end < attrs.start) {
      return "can't end before it starts";
    }
  }
});

var one = new Chapter({
  title : "Chapter One: The Beginning"
});

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

one.save({
  start: 15,
  end:   10
});
输出:false
one.toJSON()
输出:Object {title: "Chapter One: The Beginning", start: 15, end: 10}
one.save({
  start: 25,
  end:   10
});
输出:false
one.toJSON()
输出:Object {title: "Chapter One: The Beginning", start: 25, end: 10}
one.save({
  start: 35,
  end:   10
}, {validate: true});
输出:false
one.toJSON()
输出:Object {title: "Chapter One: The Beginning", start: 25, end: 10}

  

1
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics