如何从另一个对象调用对象的方法?



我正在使用 ES6 类创建自定义 UI 组件,如下所示:

class Dropdown {
constructor(dropdown) {
this.dropdown = dropdown;
this._init();
}
_init() {
//init component
}
setValue(val) {
//"public" method I want to use from another class
}
}

当页面加载时,我启动了这样的组件:

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

但是现在我需要从另一个类中访问其中一个类的方法。在这种情况下,我需要访问一个方法来设置下拉列表的值 基于 URL 参数,所以我想做这样的事情:

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...
}
}

但是当我创建此实例时,另一个下拉列表会添加到页面中,这是我不想要的。

我认为另一种方法是以这种方式在其他组件中创建组件,而不是像第一段代码那样。这是一种有效的方法吗?我应该创建另一个继承自原始类的 Dropdown 类吗?

一个简单的解决方案是将Dropdown实例存储在元素上以避免重新创建它:

class Dropdown {
constructor(element) {
if (element.dropdown instanceof Dropdown)
return element.dropdown;
this.element = element;
element.dropdown = this;
//init component
}
…
}

最新更新