我创建使用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类吗?
“*当页面加载我开始喜欢这个组件*” - 为什么?他们自己做什么?谁使用'let DropDownEl'并调用他们的公共方法? – Bergi
@Bergi其实没有人。这是显示自定义元素而不是默认元素的方式。我应该改变它吗? –
@Bergi在他们的一个将派遣事件。 –