dna

Evolution-based components.

Events

There are many ways to declare event listeners in a components library. The EventsMixin opts for a declarative system in the component definition rather than using a template engine (template and render are concepts of the TemplateMixin).

Using the events getter you can define a set of listeners for the component itself or for its children through event delegation.

import { BaseComponent, define } from '@dnajs/core';

class MyComponent extends BaseComponent {
    get events() {
        return {
            'click': 'onClick',
            'dragstart':(ev) => {  },
            'mousedown .handler': 'onStart',
            'mouseup .handler[active]': 'onFinish',
        }
    }

    onClick(ev) {
        //
    }

    onStart(ev, target) {
        // `target` is a reference to the matched element using the selector.
        // It is different from the real `ev.target`!
    }

    onFinish(ev, target) {
        //
    }
}

define('my-component', MyComponent);

The events getter returns an Object where keys are event delegation using the syntax {eventName} {selector} (when no selector is specified, the event refers to the component itself). Values can be strings (reference to the component prototype) or flying functions.

All listeners receive as first param the original event, while delegated events receive a second param, which is the selected target.

Dispatch custom events

EventsMixin provides a trigger helper to trigger custom events with custom data as details property of the event. It is just a wrapper around CustomEvent initialization and Node.prototype.dispatch method.

import { BaseComponent } from '@dnajs/core';

class MyComponent extends BaseComponent {
    get events() {
        return {
            'custom': function(ev) {
                console.log(ev.details);
            }
        };
    }
}

let elem = new MyComponent();
elm.trigger('custom', { name: 'Alan' });
// --> Object{ "name": "Alan" }