The default value will be applied only if the corresponding constructor is not passed. In this case, it is likely to ensure that the element created with the empty string as the title is displayed with something in it. Compare
var Todo1 = Backbone.Model.extend({ defaults: function() { return { title: "empty todo...", done: false }; }, initialize: function() { if (!this.get("title")) { this.set({"title": this.defaults().title}); } } }); var t1 = new Todo1({ title: "" });
with
var Todo2 = Backbone.Model.extend({ // Default attributes for the todo item. defaults: function() { return { title: "empty todo...", done: false }; } }); var t2 = new Todo2({ title: "" });
t1.get('title') will be empty todo ... and t2.get('title') will be empty string. Passing arguments to both constructors would really use the default values.
And the script is http://jsfiddle.net/nikoshr/CeEDg/
source share