I'm building a form (a razor page). There are two SelectList components, one depends on the other (see below).
While components were defined explicitly on the form page with alpine.js connected via cdn, productIdChanged event handler could access SelectList context (it had access to its disable(), enable() methods).
Since I've switched to webpack build the productIdChanged event handler's context changed to Window.
How to make these two communicate? I planned SelectList to be as much generic and reusable as possible.
<!-- this SelectList dispatches the event with product id -->
<div x-data="SelectList({ dispatchOnChange: true })" x-bind="ComponentRoot">
<select x-ref="SelectInput" name="productId" id="ProductsList">
<!-- ...options... -->
</select>
</div>
<!-- this SelectList is expected to respond to the product id change -->
<div x-data="SelectList({
eventHandlers: [
{
name: 'productIdChanged',
handler: function(e) {
console.log([e, this]);
// reset and then disable this select
}
}
]
})" x-bind="ComponentRoot">
<select x-ref="SelectInput" name="quantityUnitId" id="QuantityUnitsList">
<!-- ...options... -->
</select>
</div>
Here's the definition of the SelectList component, it's a selectr wrapper.
function SelectList({ customClass = '', searchable = false, dispatchOnChange = false, eventHandlers = [] } = {}) {
return {
init() {
// assign event handlers
eventHandlers.forEach(eh => { this.ComponentRoot[`@${eh.name}.window`] = eh.handler; });
// configure selectr
this.selectr = new Selectr(this.$refs.SelectInput, { ...customClass, searchable });
// dispatch select value
dispatchOnChange && this.selectr.on('selectr.change', (item) => {
this.$dispatch(`${this.$refs.SelectInput.name}Changed`, { id: item.value });
});
},
reset() { this.selectr.setValue(''); },
disable() { this.selectr.disable(); },
enable() { this.selectr.enable(); },
// used for x-bind
ComponentRoot: { },
};
}