我需要将模型的属性呈现给JSON,以便我可以将它们传递到模板中。 下面是一个视图渲染()函数如下:骨干模型.toJSON()不会将所有属性呈现给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/"
这里是模型的JSON console.log(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({success:function(model){goal_ullview = new GoalFullView({ model:goal, }); }});
可以告诉你的模型及其实例呢? – mindandmedia 2012-04-21 20:13:04
您的代码中还有其他属性可以让其他属性对于jSON()不可见,也许您可以查看模型或粘贴,以及如何初始化它...请参阅[jsfiddle](http://jsfiddle.net/drinchev/ JLfJB/1 /) – drinchev 2012-04-23 08:26:08
我使用Model类编辑原始帖子。我似乎无法弄清楚为什么toJSON不起作用。尽管,当我尝试执行this.model.get(“id”)或任何其他属性时,this.model.attributes会打印出正确的属性列表,但它们会显示为空。显然,当我在模型实例上调用属性时,它就存在了。 – egidra 2012-04-24 02:47:03