Skip to content

Instantly share code, notes, and snippets.

@bjcull
Created February 17, 2013 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjcull/4970183 to your computer and use it in GitHub Desktop.
Save bjcull/4970183 to your computer and use it in GitHub Desktop.
A tiny javascript event engine
var QuickEvent = function () {
var nextSubscriberId = 0;
var subscriberList = [];
var subscribe = function (callback) {
var id = nextSubscriberId;
subscriberList[id] = callback;
nextSubscriberId++;
return id;
};
var unsubscribe = function (id) {
delete subscriberList[id];
};
var trigger = function (sender) {
for (var i in subscriberList) {
subscriberList[i].apply(sender, Array.prototype.slice.call(arguments, 1));
}
};
return {
subscribe: subscribe,
unsubscribe: unsubscribe,
trigger: trigger
};
};
@notpushkin
Copy link

Just ported to CoffeeScript:

class QuickEvent
  nextSubscriberId = 0
  subscriberList = []
  subscribe: (callback) ->
    id = nextSubscriberId
    subscriberList[id] = callback
    nextSubscriberId++
    id

  unsubscribe: (id) ->
    delete subscriberList[id]

  trigger: (sender, args...) ->
    for i of subscriberList
      subscriberList[i].apply sender, args

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment