在事件中调用渲染时模型显示为未定义

Model shows as undefined when render is called at event

我有以下 initialize 方法的观点:

initialize: function(){
    this.model.on("all", this.render)
},

在渲染方法中,我使用以下方法访问模型的内容:

var contents = this.model.attributes.content;

模型的content属性是数组
因此,当我通过控制台使用 model.set() 向数组添加内容时,将调用渲染方法,但出现以下错误:Uncaught TypeError: Cannot read property 'attributes' of undefined(…).
但是如果我手动调用 view.render() 添加后,它会很好地渲染模型。
同样,如果我添加任何内容,它会抛出相同的错误。
解决方案?

因为您正在使用 this.model.on("all", this.render) 收听 您的渲染函数将获取模型作为上下文,即当调用回调时 'this' 将引用模型。尝试使用 this.listenTo(this.model, "all", this.render)。这样你就可以设置上下文了。

问题可能出在执行 rendercontextthis 的值)- 由于事件触发器。

如果您放置一个调试器并检查模型更改执行的 renderthis 的值,它不会保存 view 的引用。

您可以按照 backbone documentation:

中指定的方式将第三个参数传递给 on 来修复此问题
this.model.on( 'all', this.render, this );

第三个参数是上下文render将在其中执行。意思是,无论您作为第三个参数传递什么,都将是 render 函数中 this 的值。

最好使用 listenTo 而不是 on,因为它以比 on 更好的方式清理事件。您可以在 Whosebug 问题 Backbone js .listenTo vs .on.

上阅读对同一件事的很好解释

所以初始化应该写成:

initialize: function() {
    this.listenTo( this.model, 'all', this.render );
}

而且,我建议使用 model 中可用的 get 方法来访问它的属性,因此不要通过 this.model.attributes.content 访问 content 使用 this.model.get( 'content' ).

希望对您有所帮助:)