骨干模型默认值-todos.js示例中不必要的代码

Backbone Model defaults - unnecessary code in todos.js example?

本文关键字:不必要 代码 js 模型 默认值 -todos      更新时间:2023-09-26

在backbone.js ToDos示例中,ToDo构造函数的initialize方法将title属性设置为默认标题。

这不是没有必要吗?我认为默认值的意义在于它们是自动分配的?还是我错过了什么?

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});
      }
    },
    ///...
);}

只有在没有向构造函数传递相应属性的情况下,才会应用默认值。在这种情况下,可能是为了确保用空字符串作为标题创建的项目显示出其中的内容

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: ""
});

带有

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')将为空和CCD_ 4将是一个空字符串。不向两个构造函数传递任何参数确实会使用默认值。

和小提琴http://jsfiddle.net/nikoshr/CeEDg/