jeudi 16 juillet 2020

Registering property changes of an object from another object

In my project, I have a widgetBar that can contain one or more widgets.

When clicking on the widget icon in the widgetBar, a panel is opened to show the conent of the pressed widget (kind of a navigation bar with all dropdown menus).

Each widget is a class that has a togglePanel() method that is bind to an onlcick event on the widget's icon and openes/closes the panel. This method also sets the widget's isActive property to either true (when panel opens), or false (when panel closes).

class Widget {
    isActive: boolean = false;
    element: HTMLElement;
    id: string;

    constructor(id: string) {
        this.id = id;
        this.element = document.crateElement('DIV');
        // ... this.element and other things represent the widget DOM object
        this.element.onclick = this.togglePanel.bind(this);
    }

    togglePanel() {
        if (this.panel.classList.contains('active')) {
            this.openPanel();
            this.isActive = true;
        } else {
            this.closePanel();
            this.isActive = false;
        }
    }
}

The WidgetBar constructor takes a list of widgets as argument that becomes its this.widgets property. It also has a getWidgets() methos that gives access to this property.

class WidgetBar {
    private widgets: Widget[];

    constructor(widgets: Widget[]) {
        this.widgets = widgets;
    }

    getWidgets() {
        return this.widgets;
    }
}

The (my project's) rule is that whenever a widget opens its panel, all the other panels should be closed.

How may I automatically check from the WidgetBar if one of its widgets has changed its isActive property so that I can make sure no more than one panel at a time is opened?

I read about Proxy, but I am not sure this is what could help me solving this problem.

Aucun commentaire:

Enregistrer un commentaire