Created
February 25, 2021 12:29
-
-
Save hopsoft/9f50a9c2d17a788452ffafcad60fe5f1 to your computer and use it in GitHub Desktop.
Stimulus Controller for slim-select that supports AJAX content
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
<%= 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(...) | |
}} %> |
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
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