If you are like me, you browse Github for cool new repositories. My new hobby is looking at what the community are building for rival frameworks and one of those frameworks is Angular 2.
The Angular 2 community has done a great job of porting over not only existing libraries from Angular 1, but also creating new ones. There are some that are not available for Aurelia, but fortunately there is quite a lot of overlap between the two frameworks in ECMAScript and TypeScript syntax.
I recently encountered in one Angular 2 library the use of EventEmitter, you might be forgiven for thinking this is similar to Aurelia’s pub/sub event aggregator, but it is not. The EventEmitter is essentially a wrapper around native events you might create using the new CustomEvent(...)
constructor. Really it is more akin to Aurelia’s @bindable
decorator, both can do the same thing.
In the following example we create a DOM event and further down we use @bindable
functionality to also mimic an EventEmitter action.
import {inject} from 'aurelia-framework';
@inject(Element)
export default class MyCustomSomething {
private element: Element;
constructor(element: Element) {
this.element = element;
}
dispatchChange() {
let detail = {myArg: 'some value'};
let eventInit = {detail, bubbles: true};
let event = new CustomEvent('change', eventInit);
this.element.dispatchEvent(event);
}
}
But wait, there is more. Another more straightforward approach is using the @bindable
decorator functionality in an Aurelia class. A bindable on a class can actually be called as a function to trigger it like an event.
import {inject, bindable, customElement} from 'aurelia-framework';
@inject(Element)
@customElement('my-el')
export default class MyCustomSomething {
private element: Element;
@bindable someattr;
// The above written in Angular 2 style:
// @Output() someAttr: EventEmitter<any> = new EventEmitter();
constructor(element: Element) {
this.element = element;
}
attached() {
this.someattr({myVar1: 'myVar', myVar2: 'anotherVal'});
// The above written in Angular 2 style:
// this.someAttr.next({ myVar1: 'myVar', myVar2: 'anotherVal' });
}
}
Using the above custom element example, we have an attribute on our custom element called someattr
which we can use to call another function when it is triggered. Obviously we wouldn’t trigger an event inside of attached()
this is just an example.
<template>
<my-el someattr.call="handleEventChange(myVar1, myVar2)"></my-el>
</template>
Conclusion
Anything that Angular 2 can do, it seems Aurelia can do it more succinctly. While EventEmitter is one of the least confusing aspects of Angular I have seen, I think a native event or @bindable
gets the job done a lot easier.