SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы

Список вопросов Печать

Как сделать простую шину событий?


Метки: шина событий event bus javascript 

Ответы

RemiZOffAlex  Создано: 2023-12-21 08:27:40.050269  Обновлено: 2023-12-21 08:27:40.050282

JavaScript

function EventBus() {
    let listeners = {};
    return {
        on: function(event, callback) {
            console.log('EventBus.on');
            if (!(event in listeners)) {
                listeners[event] = [];
            }
            if (callback!=undefined) {
                listeners[event].push(callback)
            }
        },
        off: function(event) {
            console.log('EventBus.off');
            delete listeners[event];
        },
        emit: function(event, arguments) {
            console.log('EventBus.emit');
            listeners[event].forEach(element => {
                console.log(element);
                let result = element(arguments);
            });
        }
    };
};
const bus = EventBus();
bus.on('notify');

function notification_add(notification) {
    console.log(notification)
    notifications.push(notification);
};
function notification_delete(notification) {
    notifications = arrayRemove(notifications, notification);
};
bus.on('notify', notification_add)

bus.emit('notify', {
title: 'Вызов страницы',
body: response['error'].message,
typeOf: 'danger'
})

Возможно будут интересны и другие вопросы