Reputation: 8602
Here is my code:
MyModel = {
get: function(key, model) {
if(typeof(model) === 'undefined') { // A
model = Model.get(); // A
} // A
return model.data[key];
},
getAll: function(model) {
if(typeof(model) === 'undefined') {
model = Model.get();
}
return model.data;
},
save: function(data, model) {
if(typeof(model) === 'undefined') {
model = Model.get();
}
model.save(data);
},
//...
}
The A
part repeats.
Is there a way to do it more beautiful?
Something like get: function(key, model = Model.get())
;
From MDN, but it does not work in many browsers.
function setBackgroundColor(element, color = 'rosybrown') {
element.style.backgroundColor = color;
}
setBackgroundColor(someDiv); // color set to 'rosybrown'
setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' too
setBackgroundColor(someDiv, 'blue'); // color set to 'blue'
Upvotes: 0
Views: 25
Reputation: 59232
You can make it a function in your object, thus keeping your code dry
getModel: function(model){
return model || Model.get();
}
Now use the following in the blocks where you need the model.
var test_model = this.getModel(model);
Upvotes: 3
Reputation: 3295
Default Parameters are a part of ECMA 6 proposal and only work on Firefox 15.0 and up. No other browsers support it.
Upvotes: 0