Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function createEventEmitter<T>() {
- let listeners: ((action: T) => void)[] = [];
- return {
- subscribe,
- dispatch,
- };
- function subscribe(listener: (action: T) => void) {
- listeners.push(listener);
- return function unsubscribe() {
- const idx = listeners.findIndex(f => f === listener);
- listeners.splice(idx, 1);
- };
- }
- function dispatch(action: T) {
- listeners.forEach(f => f(action));
- return action;
- }
- }
- /* Demo */
- interface Foo {
- type: 'FooAction';
- payload: number;
- }
- interface Bar {
- type: 'BarAciton';
- payload: string;
- }
- type ActionTypes = Foo | Bar;
- const ee = createEventEmitter<ActionTypes>();
- ee.subscribe((action) => {
- switch (action.type) {
- case 'FooAction':
- return action.payload;
- default:
- break;
- }
- });
- ee.dispatch({ type: 'FooAction', payload: 1 });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement