我需要将模型的属性呈现为 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 中的成功回调来呈现使用模型的视图:
目标.fetch({成功:函数(模型){ var goalFullView = new GoalFullView({模型:目标,});}});