Default base model - unnecessary code in todos.js example?

In the backbone.js ToDos example , the initialize method of the ToDo constructor sets the title attribute to the default header.

Is it not necessary? I thought the reason for defaults is that they are automatically assigned? 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}); } }, ///... );} 
+4
source share
1 answer

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/

+5
source

Source: https://habr.com/ru/post/1434035/


All Articles