Created
June 10, 2017 10:57
-
-
Save javimosch/69f53dc0f7e0e04a96e4c1de1036454d to your computer and use it in GitHub Desktop.
Tiny Event system that just works
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
| /* | |
| var detach = $evt.on('foo',console.log) //Register as normal | |
| $evt.emit('foo',1,2,3) //Emit using N arguments | |
| $evt.off('foo') //Detach using name (every listener is detached) | |
| detach(); //Detach using funcion | |
| */ | |
| (function() { | |
| var arr = []; | |
| var self = window.$evt = { | |
| emit: function() { | |
| var args = Array.prototype.slice.call(arguments), | |
| n = args.splice(0, 1); | |
| (arr[n] && arr[n].length > 0 && arr[n].forEach(e => e.apply(e, args))); | |
| return (arr[n] && arr[n].length > 0) ? true : false; | |
| }, | |
| off: (t, n) => ((typeof t === 'string' && arr[t] && delete arr[t]) || (typeof t === 'function' && n !== undefined && arr[n].filter(e => e.toString() == t.toString()).length > 0 && arr[n].splice(arr[n].indexOf(t.toString()))) && true) || false, | |
| on: (n, c) => ((arr[n] && arr[n].push(c)) || (arr[n] = [c])) && (() => self.off(c, n)) | |
| }; | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment