class CustomSelect {
constructor(options) {
this.options = options
this.init();
}
init() {
this.bind();
}
bind() {
/** toggle dropdown **/
this.options.selectCurrent.onclick = (event) => {
this.options.container.classList.contains('opened') ? this.closeDropdown() : this.openDropdown()
}
}
openDropdown() {
console.log('open');
this.options.container.classList.add('opened');
}
closeDropdown() {
console.log('close');
this.options.container.classList.remove('opened');
}
}
if( document.querySelector('.custom-select') ) {
customSelectInstanse = new CustomSelect({
container : document.querySelector('.custom-select'),
selectCurrent : document.querySelector('.custom-select__current'),
dropDown : document.querySelector('.custom-select__dropdown'),
dropDownElements : document.querySelectorAll('.custom-select__dropdown-item')
})
}
openDropdown()
вне класса CustomSelect
customSelectInstanse.on(.....) { ... }
class EventEmitter {
constructor() {
this.handlers = new Map();
}
on(event, handler) {
const handlers = this.handlers.has(event) ? this.handlers.get(event) : new Set();
handlers.add(handler);
this.handlers.set(event, handlers);
}
emit(event, ...args) {
if (this.handlers.has(event)) {
const handlers = this.handlers.get(event);
for (let handler of handlers) {
handler(...args);
}
}
}
}
on
у CustomSelecton(event, callback) {
this.events.on(event, callback);
}
closeDropdown
дописываем this.events.emit('close');
а для customSelectInstanse
customSelectInstanse.on('close', () => {
console.log('Close');
});