Ismael Ordás
Ismael Ordás

Reputation: 400

How can I call an object's method from another object?

I'm creating custom UI components using ES6 classes doing something like this:

class Dropdown {

    constructor(dropdown) {
        this.dropdown = dropdown;
        this._init();
    }

    _init() {
        //init component
    }

    setValue(val) {
        //"public" method I want to use from another class
    }
}

And when the page load I initiate the components like this:

let dropdown = document.querySelectorAll(".dropdown");
if (dropdown) {
    Array.prototype.forEach.call(dropdown, (element) => {
        let DropDownEl = new Dropdown(element);
    });
}

But now I need to acces a method of one of these classes from another one. In this case, I need to access a method to set the value of the dropdown based on a URL parameter, so I would like to do something like:

class SearchPage {
//SearchPage is a class and a DOM element with different components (like the dropdown) that I use as filters. This class will listen to the dispached events
//from these filters to make the Ajax requests.

    constructor() {
        this._page = document.querySelector(".search-page")
        let dropdown = this._page.querySelector(".dropdown);
        //Previously I import the class into the file            
        this.dropdown = new Dropdown(dropdown);
    }

    setValues(val) {

        this.dropdown.setValue(val);
        //Set other components' values...
    }

}

But when I create this instance, another dropdown is added to the page, which I don't want.

I think an alternative is to create the components this way, inside other ones, and not like in the first piece of code. Is this a valid way? Should I create another Dropdown class that inherits from the original one?

Upvotes: 1

Views: 147

Answers (1)

Bergi
Bergi

Reputation: 664548

A simple solution is to store the Dropdown instance on the element to avoid re-creating it:

class Dropdown {
    constructor(element) {
        if (element.dropdown instanceof Dropdown)
            return element.dropdown;
        this.element = element;
        element.dropdown = this;

        //init component
    }
    …
}

Upvotes: 2

Related Questions