I'm new to JavaScript and probably trying to emulate Ruby with this. I use StimulusJS, but I think the question is applicable to JS in general.
My goal is to run a method (on button click) which would fetch and display all subcategories of the category from the button. The method/function would first fetch the data and then manipulate the DOM. I wanted to split these into two methods, but when I call the other method (displaySubcategories
) from within the first one (getSubcategories
) the value of event
changes. Same thing with this
in the fetch
block - I need to assign it first to self
to be be later able to related to object itself.
Is there a better way to do this? Like variables accessible to all methods (instance variables in Ruby)? Or I shouldn't be splitting these into two functions at all (not JS way)?
import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["categoryId", "categoryLabel", "subcategoryList", "subcategoryHeader"]
getSubcategories() {
let category_id = event.target.firstElementChild.value
let url = "/api/categories/" + category_id + "/subcategories?levels=1"
let self = this
let e = event
fetch(url)
.then(response => response.json())
.then(json_response => {
self.displaySubcategories(json_response, e)
})
}
displaySubcategories(json_response, event) {
subcategories.forEach(function (subcategory) {
let category_label_copy = this.cloneLabel(current_label, subcategory)
current_label.classList.add("chosen")
subcategory_list.appendChild(category_label_copy)
}, this)
}
}
expenses#getSubcategories">