dna

Evolution-based components.

Life cycle

Custom Element specifications define, as well as the constructor behavior, three life cycle callbacks for components: connectedCallback, disconnectedCallback and attributeChangedCallback.

constructor

As well as any other Class, the constructor is the initialization method for a component. It can handle instance properties and events, but it should not manipulate the DOM, so no rendering or attribute changes can be done during initialization. It just set up the component.

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

class MyComponent extends BaseComponent {
    constructor() {
        // BaseComponent initialization
        super();
        // Custom initialization
        // ...
    }
}

connectedCallback

Fires when the component has been appended to the any DOM tree. At this point, it can updated some custom attributes, interact with other elements and, most important, rendered for the first time.

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

class MyComponent extends BaseComponent {
    connectedCallback() {
        // exec all BaseComponent callbacks
        super.connectedCallback();
        // `node` property should be set now
        this.node.classList.add('flex-layout');
    }
}

disconnectedCallback

Fires when the component has been detached from a DOM tree. It could mean that it has been moved to a different position (the connectCallback will fire again then) or definitively removed. Because of no general destroyed callback is provided, it is a good practice to treat this callback for listener remotion or generic cleaning operation.

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

class MyComponent extends BaseComponent {
    connectedCallback() {
        super.connectedCallback();
        this.node.addEventListener('click', this.onClick);
    }

    onClick() {
         alert('hello!')
    }

    disconnectedCallback() {
        // exec all BaseComponent callbacks
        super.disconnectedCallback();

        this.node.removeEventListener('click', this.onClick);
    }
}

attributeChangedCallback

Fires when a component DOM attribute changes. This is a very useful callback for setting initial values or trigger changes from an upper scope. It is where you can control the state of your component.

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

class MyComponent extends BaseComponent {
    static get observedAttributes() {
        return ['hidden', 'active'];
    }

    attributeChangedCallback(attrName, oldValue, newValue) {
        // exec all BaseComponent callbacks
        super.attributeChangedCallback(attrName, oldValue, newValue);
        // custom attribute handling
        if (attrName === 'hidden') {
            if (newValue === '') {
                this.style.display = 'none';
            } else {
                this.style.display = 'block';
            }
        }
    }
}