Skip to content

Instantly share code, notes, and snippets.

@alextanhongpin
Created February 7, 2017 04:10
Show Gist options
  • Save alextanhongpin/8f29d1791ccb62aaeb639646554dbaf9 to your computer and use it in GitHub Desktop.
Save alextanhongpin/8f29d1791ccb62aaeb639646554dbaf9 to your computer and use it in GitHub Desktop.
export default class Dispatcher {
constructor() {
this._events = [];
this._service = [];
}
on(action, fn) {
if (!action) throw new Error('DispatcherError: Missing variable' + action + ' is not defined');
if (!fn || typeof fn != 'function') throw new Error('DispatcherError: ' + fn + ' is not a function');
if (!this._events[action]) this._events[action] = [];
this._events[action].push(fn);
return {
remove() {
delete this._events[action];
}
}
}
trigger(action, param) {
if (!action) throw new Error('DispatcherError: Missing variable ' + action + ' is not defined');
if (!this._events[action]) return;
this._events[action].forEach((act) => {
act(param);
});
}
off(action) {
if (!action) throw new Error('DispatcherError: Missing variable ' + action + ' is not defined');
if (!this._events[action]) return;
delete this._events[action];
console.log('dispatcher:off', this._events)
}
// create a handler here to capture the call requests
call(action, param) {
if (!this._service[action]) return;
//if (this._data[action]) throw new Error('DispatcherError: ' + action + ' already exists');
return this._service[action](param);
}
listenTo(action, ajax) {
if (this._service[action]) throw new Error('DispatcherError: ' + action + ' already exists');
this._service[action] = ajax;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment