Can I use load event?

I’m trying to use a load event to display some default text inside an element when the page loads. Is this available in Stimulus?

<p data-controller="autosave"><span id="version-id" data-action="load->autosave#sayVersion">Version info</span></p>

Which looks like this in the controller:

sayVersion(event) {
event.preventDefault()
$(event.target).html("Version " + this._version)
}

This works when I use the click event, but not load. So … does this mean Stimulus isn’t yet loaded?

I’m not sure what is your use case, but it looks that you could leverage the connect() method:

connect() {
  // update your element here
}

But if you really need to listen to global events, then this should do the trick:

<span id="version-id" data-action="load@window->autosave#sayVersion">Version info</span>
2 Likes

Great, thanks! Yes, I would normally use connect(), but this is a specific case where I was looking for something global. (And I was curious as to whether it was even possible or whether I was wasting my time.)

1 Like