Created
March 3, 2018 01:04
-
-
Save BigAB/687e7d2ba2911503cea4f65cd67215c2 to your computer and use it in GitHub Desktop.
A little snippet to use ES2018 code to old school load a bunch of UI Widgets, where the HTML configures the options of the UI widget and which element is to be enhanced with a stateful UI widget
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
const uiWidgets = { | |
draggable: class Draggable { | |
constructor({ | |
element, | |
options: { dropZones = [], dragUI = 'standard' } = {} | |
}) { | |
Object.assign(this, { | |
element, | |
dropZones, | |
dragUI, | |
}); | |
} | |
}, | |
slider: class Slider { | |
constructor({ element, options: { value = 0 } = {} }) { | |
Object.assign(this, { element, slider: true, value }); | |
} | |
} | |
} | |
const initUIWidgets = uiWidgets => Object.entries(uiWidgets) | |
.map(([widgetName, Widget]) => | |
[...document.querySelectorAll(`[data-${widgetName}]`)] | |
.map(el => { | |
const widget = new Widget({ | |
element: el, | |
options: el.dataset[widgetName] | |
? JSON.parse(el.dataset[widgetName]) | |
: {} | |
}); | |
el.uiWidgets = { | |
...el.uiWidgets, | |
[widgetName]: widget | |
}; | |
return widget; | |
}) | |
) | |
// Instatiate all widgets | |
initUIWidgets(uiWidgets); | |
/* HTML should be configured like so.. | |
<div data-slider='{ "value": 0 }'></div> | |
<div data-slider='{ "value": 127 }' data-draggable='{ "dropZones": [".el-drop-target"] }'></div> | |
<div data-slider='{ "value": 255 }'></div> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment