1. 在 backbone 的 set 方法的源码中,有如下一段代码:
// Handle both `"key", value` and `{key: value}` -style arguments.
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
这段代码应该是分别处理以下两种情况的:
note.set({title: "March 20", content: "In his eyes she eclipses..."}, {silent:true});
?此时,
attrs =?{title: "March 20", content: "In his eyes she eclipses..."};
options =?{silent:true}
book.set("title", "A Scandal in Bohemia");
?此时,
attrs["title"] =?"A Scandal in Bohemia";
options : 从代码中出以看出,此参数没有被初始化
?
当然,若改为下面这样的代码之后:
book.set("title", "A Scandal in Bohemia", {silent : true});
此时,
attrs["title"] =?"A Scandal in Bohemia";
options :{silent : true}
?
2. 在set和save方法中, ?均有如下一段代码:
// Run validation. if (!this._validate(attrs, options)) return false;
?也就是说,在真正执行set或者save方法之前,会执行上述代码(官方文档里也是这么说的)。
_validate 方法的源码原下:
_validate: function(attrs, options) {
if (options.silent || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validate(attrs, options);
if (!error) return true;
if (options && options.error) {
options.error(this, error, options);
} else {
this.trigger('error', this, error, options);
}
return false;
}
从源码中我觉得有两个地方是需要注意的:
① 当我们在set 或者 save 时,如果在 options 中传入了 {silent : true} 这个参数,那么,系统是不会调用 我们自己在Model中定义的validate方法的,因为在 ?_validate中第一行,就直接返回 true 了。
② 在Model中,我们自定义的 validate 方法中,如果校验失败,我们也不能直接返回 false ,而是返回一个字符串或者其他的对象,否则的话,从上面第四行,我们可以看到,该方法将返回true,这与我们想要的是相反的。
?
3.根据 2 中_validate方法的源码的第6行的 ? ?options.error(this, error, options); ? ? 来看,在校验失败之后,系统会调用一个 error 对应的 callback 方法,那么,这个callback 是怎么传进来的呢?答案就是,在 调用 set 方法时,将该 callback 作为一个 options 传进行来,可以参考下面的代码:
$("input[value='name']").click(function() {
var name = $("#name").val();
mt.set(
{name : name},
{error: function(context,msg,options) {alert(msg);}
});
});
?将上面的代码对照着官方的 set 方法的说明来看,
model.set(attributes, [options])
应该会比较容易理解:
?{name : name} ?是作为 attributes 的,
{error: function(context,msg,options) {alert(msg);} ?是作为 options 的
?