Add event emitter

This commit is contained in:
Pig Fang 2018-09-07 10:14:31 +08:00
parent a864adbfb8
commit f55412035d
3 changed files with 41 additions and 0 deletions

View File

@ -0,0 +1,22 @@
/** @type {{ [name: string]: Function[] }} */
const bus = Object.create(null);
/**
* @param {string} eventName
* @param {Function} listener
*/
export function on(eventName, listener) {
(bus[eventName] || (bus[eventName] = [])).push(listener);
}
/**
* @param {string} eventName
* @param {any} payload
*/
export function emit(eventName, payload) {
bus[eventName] && bus[eventName].forEach(listener => listener(payload));
}
Object.defineProperty(window, 'bsEmitter', {
get: () => Object.freeze({ on, emit })
});

View File

@ -1,6 +1,7 @@
import './public-path'; // Must be first
import './i18n';
import './net';
import './event';
import './layout';
import './logout';
import './check-updates';

View File

@ -0,0 +1,18 @@
import * as emitter from '@/js/event';
test('mount variable to global', () => {
expect(window.bsEmitter).toBeFrozen();
});
test('add listener and emit event', () => {
const mockA = jest.fn();
const mockB = jest.fn();
emitter.on('a', mockA);
emitter.on('b', mockB);
emitter.emit('a');
expect(mockA).toHaveBeenCalledTimes(1);
expect(mockB).not.toBeCalled();
});