admin管理员组文章数量:1208155
I'm wanting to set a const variable for a CSS selector for my controller, instead of having it hard coded throughout my controller. I had put the declaration in the initialize() of my controller, but I'm getting an error that the variable wasn't declared. What's the correct way of doing this?
Current Attempt
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["form"]
initialize() {
const seasonInputSelector = "input[id$='_season']"
}
change(event) {
// ...
var yearNodes = this.formTarget.querySelectorAll(seasonInputSelector)
// ...
}
}
Error: ReferenceError: seasonInputSelector is not defined
I'm wanting to set a const variable for a CSS selector for my controller, instead of having it hard coded throughout my controller. I had put the declaration in the initialize() of my controller, but I'm getting an error that the variable wasn't declared. What's the correct way of doing this?
Current Attempt
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["form"]
initialize() {
const seasonInputSelector = "input[id$='_season']"
}
change(event) {
// ...
var yearNodes = this.formTarget.querySelectorAll(seasonInputSelector)
// ...
}
}
Error: ReferenceError: seasonInputSelector is not defined
Share Improve this question asked Jun 27, 2020 at 19:34 daveomcddaveomcd 6,55516 gold badges86 silver badges142 bronze badges 1 |2 Answers
Reset to default 15Use a const
variable in the module's root scope:
import { Controller } from "stimulus"
const seasonInputSelector = "input[id$='_season']";
export default class extends Controller {
static targets = ["form"]
initialize() {
}
change(event) {
// ...
var yearNodes = this.formTarget.querySelectorAll( seasonInputSelector );
// ...
}
}
An alternative is to scope it inside your class
import { Controller } from "stimulus"
export default class extends Controller {
static targets = ["form"]
seasonInputSelector = "input[id$='_season']";
change(event) {
// ...
var yearNodes = this.formTarget.querySelectorAll( this.seasonInputSelector );
// ...
}
}
本文标签: javascriptHow can I declare a const string in my Stimulus JS controllerStack Overflow
版权声明:本文标题:javascript - How can I declare a const string in my Stimulus JS controller? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738744252a2110025.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
seasonInputSelector
as a local inside theinitialize
method. It doesn't exist outside ofinitialize
. You need to move it to be a static class-level field (as your class is anonymous you can't do this) or a const in the module's scope. – Dai Commented Jun 27, 2020 at 19:36