Skip to content

Instantly share code, notes, and snippets.

@chadwilken
Created April 12, 2018 02:02
Show Gist options
  • Save chadwilken/77dfeb0c3ccb6240d927c3c96770aedd to your computer and use it in GitHub Desktop.
Save chadwilken/77dfeb0c3ccb6240d927c3c96770aedd to your computer and use it in GitHub Desktop.
import { Controller } from 'stimulus';
export default class extends Controller {
connect() {
this.select2Mount();
document.addEventListener('turbolinks:before-cache', this.handleCache);
}
disconnect() {
document.removeEventListener('turbolinks:before-cache', this.handleCache);
}
handleCache = () => {
this.saveState();
this.select2Unmount();
}
select2Mount() {
const placeholder = this.select.data('placeholder');
const options = {};
if (placeholder) {
options['placeholder'] = placeholder
}
this.select.select2(options);
}
select2Unmount() {
this.select.select2('destroy');
}
saveState() {
const values = this.select.val();
if (!values) { return; }
if (Array.isArray(values)) {
values.forEach((val) => {
// Store selected in HTML before caching so select2 will re-init properly
this.select.find(`options[value="${val}"]`).attr('selected', 'selected');
});
} else {
this.select.find(`options[value="${values}"]`).attr('selected', 'selected');
}
}
get select() {
return $(this.targets.find('select'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment