Created
February 22, 2020 00:33
-
-
Save chamakits/0f41063c231d65302b9baa7053db7b54 to your computer and use it in GitHub Desktop.
StimulusJS Adding Elements Dynamically
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AutocompleteController extends Stimulus.Controller { | |
static get targets() { | |
return [ "results" ] | |
} | |
initialize() { | |
this.fakeFetch() | |
setInterval(this.fakeFetch.bind(this), 1500) | |
} | |
redirect(event) { | |
alert(`Redirect! "${event.currentTarget.textContent.trim()}"`) | |
} | |
fakeFetch() { | |
const length = Math.ceil(Math.random() * 20) + 2 | |
this.resultsTarget.innerHTML = Array.from({ length }, () => ` | |
<li data-action="click->autocomplete#redirect"> | |
${Math.random().toString().slice(-10)} | |
</li>` | |
).join("") | |
} | |
} | |
const application = Stimulus.Application.start() | |
application.register("autocomplete", AutocompleteController) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- from: https://jsfiddle.net/javan/x4p8n7mb/ --> | |
<div data-controller="autocomplete"> | |
<ul data-target="autocomplete.results"></ul> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment