-
-
Save jansim/b3384836b0bdf0706bb1ad1264913891 to your computer and use it in GitHub Desktop.
Really simple Javascript custom event system (slightly extended to keep listeners and allow whether stuff should be called immediately)
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 Event = function () { | |
var self = this | |
self.queue = {} | |
self.fired = [] | |
return { | |
fire: function (event) { | |
var queue = self.queue[event] | |
if (typeof queue === 'undefined') { return } | |
queue.forEach((callback) => callback()) | |
self.fired[event] = true | |
}, | |
on: function (event, callback, callIfFired) { | |
if (callIfFired && self.fired[event] === true) { callback() } | |
if (typeof self.queue[event] === 'undefined') { | |
self.queue[event] = [] | |
} | |
self.queue[event].push(callback) | |
}, | |
off: function (event, callback) { | |
var queue = self.queue[event] | |
if (typeof queue === 'undefined') { return } | |
if (callback) { | |
var index = queue.indexOf(callback) | |
if (index > -1) { queue.splice(index, 1) } | |
} else { | |
delete self.queue[event] | |
} | |
} | |
} | |
}() | |
// Basic usage | |
Event.on('counted.to::1000', function () { | |
doSomething() | |
}) | |
for (i = 0; i <= 1000; i++) { | |
// Count to 1000... | |
} | |
Event.fire('counted.to::1000'); // doSomething() is called | |
// doThisImmediately() is called immediately, since we provide callIfFired as true | |
Event.on('counted.to::1000', function () { doThisImmediately() }, true) | |
// dontDoThisImmediately() is *not* called, since we do *not* provide callIfFired | |
Event.on('counted.to::1000', function () { dontDoThisImmediately() }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment