骨干模型.toJSON()不会将所有属性呈现给JSON

egi*_*dra 10 javascript backbone.js

我需要将模型的属性呈现给JSON,以便将它们传递给模板.以下是视图的render()函数:

render: function() {
  console.log(this.model);
  console.log(this.model.toJSON());
  $(this.el).html(this.template(this.model.toJSON()));
  return this;
},
Run Code Online (Sandbox Code Playgroud)

这是执行console.log(this.model)后输出的属性:

created_at: "2012-04-19"
id: "29"
name: "item"
resource_uri: "/api/v1/item/29/"
updated_at: "2012-04-21"
user: "/api/v1/user/9/"
Run Code Online (Sandbox Code Playgroud)

这是执行console.log(this.model.toJSON())后模型的JSON输出:

id: "29"
__proto__: Object
Run Code Online (Sandbox Code Playgroud)

发生了什么?

编辑:这是实例化:

  var goal = new Goal({id: id});
  goal.fetch();
  var goalFullView = new GoalFullView({
    model: goal,
  });
Run Code Online (Sandbox Code Playgroud)

以下是新视图的内容:

  console.log(this.model.attributes);
  console.log(this.model.toJSON());
Run Code Online (Sandbox Code Playgroud)

这是控制台说的:

Object
created_at: "2012-04-23"
id: "32"
name: "test"
resource_uri: "/api/v1/goal/32/"
updated_at: "2012-04-23"
user: "/api/v1/user/9/"
__proto__: Object

Object
id: "32"
name: "test"
__proto__: Object
Run Code Online (Sandbox Code Playgroud)

如果toJSON应该复制属性,为什么不复制正确的名称或为什么不复制created_at,updated_at字段?

编辑2:这是模型:

  var Goal = Backbone.Model.extend({

    // Default attributes for Goal
    defaults: {
      name: "empty goal",
    },

    // Check that the user entered a goal
    validate: function(attrs) {
      if (!attrs.name) {
        return "name is blank";
      }
    },

    // Do HTTP requests on this endpoint
    url: function() {
      if (this.isNew()) {
        return API_URL + "goal/" + this.get("id") + FORMAT_JSON;
      }
      return API_URL + "goal/" + FORMAT_JSON;
      //API_URL + "goal" + FORMAT_JSON, 
    },
  });
Run Code Online (Sandbox Code Playgroud)

编辑3:我发现我需要使用来自fetch的成功回调来渲染使用该模型的视图:

goal.fetch({success:function(model){var goalFullView = new GoalFullView({model:goal,});}});

jim*_*imr 27

toJSON()方法只返回模型attributes属性的浅层克隆.

从带注释的Backbone.js源代码:

toJSON: function(options) {
  return _.clone(this.attributes);
}
Run Code Online (Sandbox Code Playgroud)

在没有看到更多代码的情况下,看起来您直接在模型对象上设置属性,而不是使用该set函数来设置模型属性.

即不要这样做:

model.name = "item";
Run Code Online (Sandbox Code Playgroud)

做这个:

model.set("name", "item");
Run Code Online (Sandbox Code Playgroud)

编辑:

对于您的特定问题,您可能在模型完成从服务器加载之前调用了toJSON.

例如,这并不总是按预期工作:

var model = new Goal({id: 123});
model.fetch();
console.log(model.toJSON());
Run Code Online (Sandbox Code Playgroud)

但这会:

var model = new Goal({id: 123});
model.fetch({
  success: function() {
    console.log(model.toJSON());
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 替代集语法:`model.set({name:"item"})` - 此表单允许您同时设置许多属性. (3认同)