gpt4 book ai didi

backbone.js - 在 View 类中丢失 Backbone this 上下文

转载 作者:行者123 更新时间:2023-12-02 07:41:49 25 4
gpt4 key购买 nike

在呈现嵌套 View 时,我的 this 上下文丢失了。这是我的代码:

Workflow.Views.Wall = Backbone.View.extend({
tagName: 'div',
id: 'wall',
className: 'row-fluid span12',

initialize: function() {
_.bindAll(this, 'render');
this.model.view = this;
},

render: function() {
this.model.stages.each(this.renderStage);
return this;
},

renderStage: function(model) {
var stageView = new Workflow.Views.Stage({ model: model });
//this is DOMWindow
this.$el.append(stageView.el);
}
});

所以一堵“墙”有很多“阶段”。在我的 renderStage 函数中,this 是 DOMWindow。

有人看到我的错误吗?

最佳答案

您需要将您的 renderStage 方法绑定(bind)到 Workflow.Views.Wall View ...基本上这样您就有了正确的 this 上下文.

initialize: function() {
_.bindAll(this, 'render', 'renderStage');
this.model.view = this;
}

或者,您可以只调用 _.bindAll 而没有方法参数,这将自动将 this 绑定(bind)到 所有 方法:

_.bindAll(this);

如需进一步阅读,请参阅 Understanding bind and bindAll in Backbone .另请参阅 _.bindAll 的文档.

关于backbone.js - 在 View 类中丢失 Backbone this 上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com