I want to do simple thing with a model:
- use constructor parameters if they are valid (but not just assign them, I have to map them before as they are in a different format)
- in other case, use
defaults
What's the recomended solution for this?
You can achieve this by calling isValid() in initialize. If it's valid, then proceed as normal; otherwise, clear the model and reset it with the default values:
initialize: function() {
console.log("initializing model...");
if (!this.isValid()) {
console.log("Model is not valid, using defaults");
this.clear({ silent: true });
this.set(this.defaults, { silent: true });
}
console.log("Model is valid");
},
Edit
It's possible to use objects in the model constructor, for example:
var model = new Backbone.Model({
title: "test",
hsa: {
h: 120,
s: "100%",
a: "50%"
}
});
You could also specify it as hsa: "120, 100%, 50%" or something, and convert that value to an object in the constructor.