我正在使用 Backbone 和 Marionette,我正在从后端检索我的模型。
这些模型属于一个集合。问题是:
1) 除非在初始化中显式调用,否则永远不会调用 validate 方法。为什么?
2) 当我显式调用 validate 方法时,它会正确返回我为测试创建的无效模型。但我无法捕捉到“无效”事件。我究竟做错了什么?
这是模型:
var Job = Backbone.Model.extend({
validate: function(attrs){
if (! attrs.title ) {
return "A job should have a title";
}
},
initialize: function(){
this.validate(this.attributes); //manual call to validate
this.on("invalid", function(model, error){ //never executed even when the validate model returns the error string
console.log(error);
});
}
});
这里是集合:
var JobList = Backbone.Collection.extend({
model: Job,
url: '/api/1.0/jobs/',
parse: function(response) {
return response.results;
}
});