Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Really simple Javascript custom event system
var Event = function() {
var self = this;
self.queue = {};
self.fired = [];
return {
fire: function(event) {
var queue = self.queue[event];
if (typeof queue === 'undefined') {
return;
}
while (queue.length) {
(queue.shift())();
}
self.fired[event] = true;
},
on: function(event, callback) {
if (self.fired[event] === true) {
return callback();
}
if (typeof self.queue[event] === 'undefined') {
self.queue[event] = [];
}
self.queue[event].push(callback);
}
};
}();
// 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
@chris-pauley

This comment has been minimized.

Copy link

commented Mar 18, 2017

This is really nice, thanks for sharing! Personally I need to setup a system where an callback is called every time an event is fired, so I've modified lines 17-19 to be queue.forEach((callback) => callback()); which works nicely. Thanks for sharing!

@ttomdewit

This comment has been minimized.

Copy link

commented Mar 22, 2017

Thank you, both @chris-pauley and @wildlyinaccurate. I needed the forEach method Chris shared, but not in es6 mode:

queue.forEach(function (callback) {
    callback();
});
@screets

This comment has been minimized.

Copy link

commented Jul 9, 2017

@ttomdewet forEach method is actually supported by IE9+ already. You can use it safely. MDN - forEach

@theluk

This comment has been minimized.

Copy link

commented Nov 10, 2017

@screets it think he meant the es6 arrow callback...

@AGMETEOR

This comment has been minimized.

Copy link

commented Apr 22, 2019

@wildlyinaccurate thanks a bunch. I think self.fired should be an object self.fired = {}

@nicothed

This comment has been minimized.

Copy link

commented Aug 20, 2019

Very nice piece of code, thanks!

I've moved the
self.fired[event] = true;
line in "fire" to the top of the function. Otherwise, it's not called if fire is called before on (IMHO).

I've also added:
await: async function (event) { // usage (in an async function): await Event.await("counted.to::1000") return new Promise(async function (resolve, rejectUNUSED) { du.eventsQueue.on(event, resolve) }) },

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.