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

时间:2012-04-21 19:59:09

标签: 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;
},

执行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/"

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

id: "29"
__proto__: Object

发生了什么事?

编辑: 这是实例化:

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

以下是新视图的内容:

  console.log(this.model.attributes);
  console.log(this.model.toJSON());

以下是控制台所说的内容:

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

如果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, 
    },
  });

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

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

1 个答案:

答案 0 :(得分:27)

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

来自annotated Backbone.js source

toJSON: function(options) {
  return _.clone(this.attributes);
}

如果没有看到更多代码,看起来就像直接在模型对象上设置属性,而不是使用set函数来设置模型属性。

即。不要这样做:

model.name = "item";

这样做:

model.set("name", "item");

编辑:

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

E.g。这并不总是按预期工作:

var model = new Goal({id: 123});
model.fetch();
console.log(model.toJSON());

但这会:

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