Last active
January 5, 2023 13:35
-
-
Save tofikhidayatxyz/57ac5014b75797bd93a20330a858cf22 to your computer and use it in GitHub Desktop.
Rendering and watch select2 using alpine.js
This file contains hidden or 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 Select2Alpine { | |
| constructor(el) { | |
| this.el = document.querySelector(el); | |
| if (!this.el) { | |
| throw `Element ${el} not found`; | |
| } | |
| } | |
| init() { | |
| this.render(); | |
| return this; | |
| } | |
| watch(callback) { | |
| this.select2.on('select2:select', callback); | |
| return this; | |
| } | |
| setValue(value) { | |
| this.select2.val(value).trigger('change'); | |
| return this; | |
| } | |
| setData(data) { | |
| this.el.innerHTML = ''; | |
| data.forEach((dt) => { | |
| const optionData = new Option(); | |
| optionData.value = dt.value; | |
| optionData.textContent = dt.label; | |
| optionData.selected = dt.selected; | |
| this.el.appendChild(optionData); | |
| }); | |
| return this; | |
| } | |
| render() { | |
| this.select2 = $(this.el).select2(); | |
| return this; | |
| } | |
| destroy() { | |
| this.select2.select2('destroy'); | |
| return this; | |
| } | |
| reRender() { | |
| this.destroy(); | |
| this.render(); | |
| return this; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment