如果stimulus.js中的TargetConnected方法中存在assign变量,则全局变量未定义



这是html代码要访问的位置控制器文件。

export default class extends Controller {
static targets = [ "visible", "map" ]
mapTargetConnected(element) {
this.name = "aaa"
}
add(event) {
console.log(this.name) // this line is logged that variable is undefined.
}
}

这是HTML代码

<%= form_with(model: @location, local: false, url: location_path(), data: {controller: 'location', action: 'ajax:beforeSend->location#add'}) do |form| %>
....
<% end %>

这是关于通过ajax请求提交表单的代码。如果我访问add方法内的this.name变量或单击事件,它会说变量未定义…但如果我在connect((方法中分配相同名称的变量,则它将工作…

但我想在targetConnected方法中分配变量,并在add操作方法中使用它。请提出任何解决方案,或者如果我做错了,请告诉我。

add事件很可能是在mapTargetConnected运行之前触发的。

Stimulus将遍历DOM,匹配元素及其目标,然后在设置控制器后触发相关的someTargetConnectedconnect生命周期方法。

然而,这不是即时的,当你处理其他事件时,时间安排可能会有一些细微差别。

您需要确定实际的map目标何时添加到DOM,并可能进行一些日志记录,以检查与ajax:beforeSend事件触发时相比的时间。

有时,添加setTimeout可以起到帮助作用,因为它可以确保提供给它的代码"最后"运行(这有一些细微之处,从技术上讲,这是下一个事件周期(。

例如

add(event) {
// here the mapTargetConnected may not have run
setTimeout(() => {
// by this point, mapTargetConnected has hopefully now run
console.log(this.name);
});
}

如果没有更多关于ajax:beforeSend是什么、它何时触发以及map目标实际添加到DOM的细节,很难提供更多帮助。用最初呈现的HTML输出(用最少的部分来帮助指导问题(来写这个问题可能会更有帮助。

总的来说,最好记住,在浏览器中,事情不会立即发生,虽然可能很快,但可能存在需要注意的时间问题。

最新更新