Last active
January 6, 2017 06:50
-
-
Save chendi0x7C00/a6a2ea3442cbd661e0de78d8c768456f to your computer and use it in GitHub Desktop.
A good example of using ES6 WeakMap
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
| // https://github.com/hugeen/burst/blob/master/core/event.js | |
| // http://stackoverflow.com/questions/29413222/what-are-the-actual-uses-of-es6-weakmap | |
| // the main strength of WeakMap is that it does not interfere with garbage collection given that they do not keep a reference | |
| var listenableMap = new WeakMap(); | |
| export function getListenable (object) { | |
| if (!listenableMap.has(object)) { | |
| listenableMap.set(object, {}); | |
| } | |
| return listenableMap.get(object); | |
| }; | |
| export function getListeners (object, identifier) { | |
| var listenable = getListenable(object); | |
| listenable[identifier] = listenable[identifier] || []; | |
| return listenable[identifier]; | |
| }; | |
| export function on (object, identifier, listener) { | |
| var listeners = getListeners(object, identifier); | |
| listeners.push(listener); | |
| globalEmit('listener added', object, identifier, listener); | |
| }; | |
| export function removeListener (object, identifier, listener) { | |
| var listeners = getListeners(object, identifier); | |
| var index = listeners.indexOf(listener); | |
| if(index !== -1) { | |
| listeners.splice(index, 1); | |
| } | |
| globalEmit('listener removed', object, identifier, listener); | |
| }; | |
| export function emit (object, identifier, ...args) { | |
| var listeners = getListeners(object, identifier); | |
| for (var listener of listeners) { | |
| listener.apply(object, args); | |
| } | |
| }; | |
| export var globalEvents = {}; | |
| export function globalOn (identifier, listener) { | |
| on(globalEvents, identifier, listener); | |
| }; | |
| export function globalEmit (identifier, ...args) { | |
| emit(globalEvents, identifier, ...args); | |
| }; | |
| export function globalRemoveListener (identifier, listener) { | |
| removeListener(globalEvents, identifier, listener); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment