Skip to content
Snippets Groups Projects
component.ts 1010 B
Newer Older
David Sehnal's avatar
David Sehnal committed
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

import { PluginContext } from './context';
import { shallowMergeArray } from 'mol-util/object';
import { RxEventHelper } from 'mol-util/rx-event-helper';
David Sehnal's avatar
David Sehnal committed

export class PluginComponent<State> {
    private _ev: RxEventHelper;
David Sehnal's avatar
David Sehnal committed

    protected get ev() {
        return this._ev || (this._ev = RxEventHelper.create());
    }

    private _state: State;

    protected updateState(...states: Partial<State>[]): boolean {
        const latest = this.state;
David Sehnal's avatar
David Sehnal committed
        const s = shallowMergeArray(latest, states);
        if (s !== latest) {
            this._state = s;
David Sehnal's avatar
David Sehnal committed
            return true;
David Sehnal's avatar
David Sehnal committed
        }
David Sehnal's avatar
David Sehnal committed
        return false;
David Sehnal's avatar
David Sehnal committed
    }

    get state() {
        return this._state;
David Sehnal's avatar
David Sehnal committed
    }

    dispose() {
        if (this._ev) this._ev.dispose();
David Sehnal's avatar
David Sehnal committed
    }

    constructor(public context: PluginContext, initialState: State) {
        this._state = initialState;
David Sehnal's avatar
David Sehnal committed
    }
}