Add event emitter
This commit is contained in:
parent
a864adbfb8
commit
f55412035d
22
resources/assets/src/js/event.js
Normal file
22
resources/assets/src/js/event.js
Normal 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 })
|
||||
});
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import './public-path'; // Must be first
|
||||
import './i18n';
|
||||
import './net';
|
||||
import './event';
|
||||
import './layout';
|
||||
import './logout';
|
||||
import './check-updates';
|
||||
|
|
|
|||
18
resources/assets/tests/js/event.test.js
Normal file
18
resources/assets/tests/js/event.test.js
Normal 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();
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user