If I have a list of tasks, the list is a turbo stream with a number of turbo frames. When the index page is loaded, I want to sometimes provide an URL parameter for the id of the list item and click the link for that item to pop up a modal.
import { Controller } from '@hotwired/stimulus'
export default class extends Controller {
static itemId
connect () {
this.itemId = this.getUrlParam("pitch_id", null)
document.addEventListener("turbo:frame-load", this.openItem)
}
disconnect () {
}
openItem() {
if (this.itemId !== null && this.itemId !== undefined) {
document.removeEventListener("turbo:frame-load", this.openItem)
document.querySelector(`#item_${this.itemId}`).querySelector('li').querySelector('a').click()
}
}
get UrlVars () {
const vars = {}
const parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value
})
return vars
}
getUrlParam (parameter, defaultvalue) {
let urlparameter = defaultvalue
if (window.location.href.indexOf(parameter) > -1) {
urlparameter = this.UrlVars[parameter]
}
return urlparameter
}
}
This is my first silly attempt and it isn’t working. The itemId
is parsed ok but something is off in the callback method and it is undefined there. Anyone know how I can make this work?