2017-07-30 142 views
1

我创建使用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类吗?

+0

“*当页面加载我开始喜欢这个组件*” - 为什么?他们自己做什么?谁使用'let DropDownEl'并调用他们的公共方法? – Bergi

+0

@Bergi其实没有人。这是显示自定义元素而不是默认元素的方式。我应该改变它吗? –

+0

@Bergi在他们的一个将派遣事件。 –

回答

2

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

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

     //init component 
    } 
    … 
} 
+0

什么是“元素”在这里?它是下拉菜单吗? –

+0

@IsmaelOrdás是的,我将它重命名为更合适的'element'。 'SearchPage'有一个'dropdown','Dropdown'有一个''element'',而不是另一个'dropdown'。 – Bergi

+0

我仍然没有看到它,因为我传递给构造函数的是一个DOM元素。你能否提供另一个用法示例? 此外,在其父对象内创建实例是一个有效的解决方案? (在这种情况下,SearchPage类)而不是在页面加载时创建。 –

相关问题