Dispatch change events in custom components

This is the first post about Aurelia and the Kendo-UI-Bridge. It’s a brave new world for me.

The goal was to create a custom component (which wraps a ak-combobox) and dispatch a change event in a similar way to the standard components (i.e ak-combobox, ak-datepicker, etc.).

<input ak-datepicker="k-value.two-way: model.date" k-on-change.delegate="onChange($event)"/>

For these components, the change event is dispatched after the model changes.

In my component code I had initially wrapped the k-on-change from the base component and continued dispatching it.
This however did not had the desired effect. The wrapping component emitted the event before the model was updated (binding was updated).

<dictionary-combo value.two-way="model.currency" k-on-change.delegate="onChange($event)"></dictionary-combo>
    onChange(event){
       event.stopPropagation();
       this.dispatch()
    }
 
    dispatch(){
      this.dispatchCustomEvent(this.element, "k-on-change", {value: this.value});
    }
 
    dispatchCustomEvent(element:Element, type:string, detail:Object, bubbles:boolean){
        let newEvent;
        if (window.CustomEvent) {
            newEvent = new CustomEvent(type, {
                detail: detail,
                bubbles: true
            });
        } else {
            newEvent = document.createEvent('CustomEvent');
            newEvent.initCustomEvent(type, bubbles, true, {
                detail: detail
            });
        }
        element.dispatchEvent(newEvent);
    }

The solution is to delay the event. Stop propagating the initial event and add the action of sending the new event to the aurelia taskQueue. This would ensure the event occurs after the binding and can be done:

    onChange(event){
       event.stopPropagation();
       console.log("dictionaryCombo.onChange: " + this.value);
       //wrong way: this.dispatch()
       this.taskQueue.queueMicroTask(() => this.dispatch());
    }

Refer to this gist for complete example.

Please note that I found this, thanks to the wonderful guys on the aurelia-kendo-ui gitter to which I remain grateful
 

Leave a Reply

*