我很困惑,需要一些帮助。
我在渲染函数中并且有以下三个调试行:
console.debug(this.model);
foo = this.model.toJSON();
console.debug(foo);
第一行的输出是一个模型实例,其中包含从服务器获取的数据,并且 attributes 属性填充了我所期望的内容。
但是,第二个 console.debug 调用包含一个空对象。
什么给了?调试输出的第二位不应该包含相同的属性但 JSONified 吗?
下面是完整的代码:
function get_race() {
var RaceModel = Backbone.Model.extend({
urlRoot: api_root + 'race/1/?format=json',
});
var RaceView = Backbone.View.extend({
template: _.template('<h1>a template</h1><h2>desc: <%= year %></h2>'),
initialize: function() {
this.model = new RaceModel();
this.model.fetch();
this.render();
},
render: function() {
console.debug(this.model);
foo = this.model.toJSON();
console.debug(foo);
this.$el.html(this.template(this.model));
return this;
}
});
var race_view = new RaceView({ el: $("#backbone_test") });
最佳答案
我认为正在发生的事情是在获取模型之前调用渲染。您应该在调用 fetch 之前将其放入 initialize 并删除对 render 的调用。
this.listenTo(this.model, "change", this.render);
当像那样直接调用 render 时,this.model.toJSON() 将返回一个空对象,因为此时那里什么都没有。但是您的调试器将在获取时更新 this.model,因为它正在显示引用。
为了证明这一点,尝试记录一些不可变的东西,比如 console.log(JSON.stringify(this.model));
关于javascript - 了解 backbone.js 属性和 toJSON(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15048167/