[英]Backbone.js model, specifying attributes
I was wondering if there's a way to specify model attributes that must be initialized upon instantiation. 我想知道是否有一种方法来指定必须在实例化时初始化的模型属性。
Book = Backbone.Model.extent({
title: "title",
author: "author",
year: "year"
});
and whenever I instantiate the model, I wish to constrain that these few attributes have to be initialized, or at least constrain enough not to be able to set a new attribute: 每当我实例化模型时,我希望限制这几个属性必须初始化,或者至少足以限制不能设置新属性:
var book = new Book({
title: "something",
pages: "350"
});
Try this : 尝试这个 :
Book = Backbone.Model.extent({
defaults: {
title: "title",
author: "author",
year: "year"
}
});
If you want to constrain to those attribute you can do it using validate
method : 如果要约束这些属性,可以使用validate
方法执行此操作:
Book = Backbone.Model.extent({
defaults: {
title: "title",
author: "author",
year: "year"
},
validate: function(attrs, options) {
var isValid = true;
_.each(_.keys(attrs), function(key) {
if (!this.defaults[key]) {
isValid = false;
}
}, this);
return isValid;
}
});
try 尝试
Book = Backbone.Model.extend({
defaults: {
title: "title",
author: "author",
year: "year"
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.