Last active
January 22, 2016 11:08
-
-
Save dhoko/9ef1517c56401bbea6c5 to your computer and use it in GitHub Desktop.
Dispatcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const dispatcherApp = dispatcher('App'); | |
| const eventChange = dispatcherApp | |
| .on('change', data => { | |
| console.log('App.change', data); | |
| }) | |
| const eventTest = dispatcherApp | |
| .on('test', data => { | |
| console.log('App.test', data); | |
| eventTest(); | |
| }); | |
| dispatcherApp.dispatch('change', 'monique'); | |
| setTimeout(() => { | |
| dispatcherApp.dispatch('test', 'coucou'); | |
| }, 1000) | |
| setTimeout(() => { | |
| dispatcherApp.dispatch('test', 'coucou 2'); | |
| }, 3000) | |
| setTimeout(() => { | |
| dispatcherApp.dispatch('change', 'monique 2'); | |
| }, 2000) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const dispatcher = name => { | |
| let map = {}; | |
| const noop = () => {}; | |
| const getEventList = key => { | |
| const event = name + key; | |
| if (!map[event]) { | |
| map[event] = []; | |
| } | |
| return map[event]; | |
| } | |
| const dispatch = (key, data) => getEventList(key).forEach(cb => cb(data)); | |
| const on = (key, callback = noop) => { | |
| const event = name + key; | |
| const eventList = getEventList(key); | |
| eventList.push(callback); | |
| map[event] = eventList; | |
| return () => { | |
| const index = map[event].indexOf(callback) | |
| map[event].splice(index, 1); | |
| }; | |
| }; | |
| return {on, dispatch}; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment