骨干模型.toJSON()不会使所有属性JSON(Backbone model .toJSON()

2019-06-23 20:32发布

我需要渲染模型对JSON属性,所以我可以将它们传递到模板。 这里是一个渲染什么()的视图功能是这样的:

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后模型的JSON输出(this.model.toJSON()):

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:我想通了,我需要使用成功回调从取来呈现使用模型视图:

goal.fetch({成功:函数(模型){风险goalFullView =新GoalFullView({模型:目标,});}});

Answer 1:

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

从注释Backbone.js的来源 :

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

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

即不这样做:

model.name = "item";

做这个:

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

编辑:

为了您的具体问题,它可能是你叫的toJSON模型已经从服务器完成载入之前。

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

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());
  }
});


文章来源: Backbone model .toJSON() doesn't render all attributes to JSON