Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Created February 25, 2021 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hopsoft/9f50a9c2d17a788452ffafcad60fe5f1 to your computer and use it in GitHub Desktop.
Save hopsoft/9f50a9c2d17a788452ffafcad60fe5f1 to your computer and use it in GitHub Desktop.
Stimulus Controller for slim-select that supports AJAX content
<%= select_tag column_name,
options_for_select(...), {
multiple: true,
placeholder: "Select multiple...",
data: {
controller: "select",
action: "stimulus-reflex:after@document->select#delayedSetup",
options_url: typeahead_path(...)
}} %>
import ApplicationController from './application_controller'
import debounce from 'debounce'
import SlimSelect from 'slim-select'
export default class extends ApplicationController {
connect () {
super.connect()
this.setup()
}
disconnect (event) {
this.cleanup()
}
setup (event) {
this.cleanup()
const options = {
select: this.element,
hideSelectedOption: true,
addable: this.addable ? value => value : null,
allowDeselect: this.allowDeselect,
placeholder: this.placeholder
}
if (this.optionsUrl) {
const url = this.optionsUrl
const _ajax = (query, callback) => {
fetch(url.replace('QUERY', query))
.then(response => response.json())
.then(json => callback(json))
.catch(error => callback(false))
}
const ajax = debounce(_ajax, 250)
options.searchingText = 'Searching...'
options.ajax = ajax
}
this.slimSelect = new SlimSelect(options)
}
delayedSetup (event) {
setTimeout(this.setup.bind(this))
}
cleanup (event) {
if (!this.slimSelect) return
this.slimSelect.destroy()
delete this.slimSelect
}
get addable () {
return this.element.dataset.addable === 'true'
}
get allowDeselect () {
return this.element.dataset.allowDeselect === 'true'
}
get optionsUrl () {
return this.element.dataset.optionsUrl
}
get placeholder () {
return this.element.getAttribute('placeholder')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment