In the backbone.js ToDos example, The initialize method of the ToDo constructor sets the title attribute to the default title.
Isn’t this unnecessary? I thought the point of defaults is that they get assigned automatically? Or am I missing something?
var Todo = Backbone.Model.extend({
// Default attributes for the todo item.
defaults: function() {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
},
// Ensure that each todo created has `title`.
initialize: function() {
if (!this.get("title")) {
this.set({"title": this.defaults().title});
}
},
///...
);}
A default value will only be applied if no corresponding attribute is passed to the constructor. In this case, it’s probably to ensure that an item created with an empty string as a title gets displayed with something in it. Compare
with
t1.get('title')will be empty todo… andt2.get('title')will be an empty string. Passing no argument to both constructors would indeed use the default values.And a Fiddle http://jsfiddle.net/nikoshr/CeEDg/