Last active
March 24, 2020 02:02
-
-
Save viranmalaka/a4a1fcc138cd801c31601b30ae36768b to your computer and use it in GitHub Desktop.
Event Emmiter
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
import storeUpdates from './storeUpdates'; | |
export const STORE = { | |
ACTION_STORE: { | |
count: 999, | |
init: false, | |
}, | |
DATA_STORE: {}, | |
func: { | |
emit: (key, data) => { | |
if (STORE.ACTION_STORE[key]) { | |
// check the action is in the store | |
for (let i in STORE.ACTION_STORE[key]) { | |
// call all the functions that are define under the key | |
STORE.ACTION_STORE[key][i].fn(data || undefined); | |
} | |
} | |
}, | |
// add listeners | |
on: (key, fn) => { | |
if (STORE.ACTION_STORE[key]) { | |
// check store has that key already | |
// push to actions array | |
STORE.ACTION_STORE[key].push( | |
{ key: ++STORE.ACTION_STORE.count, fn } | |
); | |
} else { | |
// create action array | |
STORE.ACTION_STORE[key] = [ | |
{ key: ++STORE.ACTION_STORE.count, fn } | |
]; | |
} | |
return STORE.ACTION_STORE.count; | |
}, | |
// clear the listeners from the action store. | |
clear: (obj) => { | |
Object.keys(obj).forEach((k) => { | |
STORE.ACTION_STORE[k] = STORE.ACTION_STORE[k] | |
.filter(({ key }) => !obj[k].includes(key)); | |
}); | |
}, | |
init: () => { | |
!STORE.ACTION_STORE.init && storeUpdates(); | |
}, | |
}, | |
}; | |
export const createStoreUpdater = (actionName, key) => { | |
STORE.func.on(actionName, (data) => { | |
STORE.DATA_STORE[key] = data; | |
}); | |
}; | |
export const setInitStore = (obj) => { | |
STORE.DATA_STORE = obj; | |
STORE.ACTION_STORE.init = true; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment