Events

Akili events system based on the native javascript. To bind an event in the template you need:

<my-component on-click="${ this.example = 'Hello' }">${ this.example }</my-component>

Then if we click on the element, the expression inside will be replaced by Hello. You can use any native events just adding dash after on. on-click, on-keyup, on-input, etc.

You also have access to events in the component attributes.

import EventEmitter from 'akili/scr/event-emitter';

class MyComponent extends Akili.Component {
  compiled() {
    console.log(this.attrs.onClick instanceof EventEmitter); // true
  }
}

We can trigger a new event any time we want.

class MyComponent extends Akili.Component {
  compiled() {
    setTimeout(() => {
      this.attrs.onClick.trigger();
    }, 1000);
  }
}

Custom events

You can work with your custom events. At first, you need to register the event to be sure that the corresponding attribute has an event emitter even the user doesn't specify it in the template.

class MyComponent extends Akili.Component {
  static events = ['my-event'];

  compiled() {
    console.log(this.attrs.onMyEvent) // EventEmitter instance
    console.log(this.attrs.onMyEventTwo) // EventEmitter instance
    console.log(this.attrs.onMyEventThree) // undefined
  }
}
<my-component on-my-event-two="${ console.log(event) }"></my-component>

The event might include some information.

class MyComponent extends Akili.Component {
  static events = ['my-event'];

  compiled() {
    let myInformation = 'Hello';

    this.attrs.onMyEvent.trigger(myInformation);
  }
}
<my-component on-my-event="${ console.log(event.detail) // Hello }"></my-component>

In the event expressions it is always an event object (native javascript event: Event, CustomEvent e.t.c). The custom information is presented in event.detail.

By default, all events uses CustomEvent for triggering.

class MyComponent extends Akili.Component {
  static events = ['my-event'];

  compiled() {
    this.attrs.onMyEvent.trigger('Hello', { bubbles: true });
  }
}

It is the same that:

class MyComponent extends Akili.Component {
  static events = ['my-event'];

  compiled() {
    this.el.dispatchEvent(new CustomEvent('my-event', { bubbles: true, detail: 'Hello' })));
  }
}

If you need to change event class you can use dispatch method.

class MyComponent extends Akili.Component {
  static events = ['my-event'];

  compiled() {
    this.attrs.onMyEvent.dispatch(Event, { bubbles: true, detail: 'Hello' });
    this.attrs.onMyEvent.dispatch(MouseEvent, { bubbles: false });
    this.attrs.onMyEvent.dispatch(KeyEvent);
  }
}

System events

All components have a particular system events corresponding to the stages of the compilation.

<my-component
  on-compiled="${ // when it's compiled }"
  on-resolved="${ // when it's resolved }"
  on-recompiled="${ // when it's recompiled }"
  on-removed="${ // when it's removed }"
></my-component>