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 :
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"
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.