Skip to content

Instantly share code, notes, and snippets.

@sukima
Forked from neoGeneva/gist:1309070
Last active December 12, 2015 00:28
Show Gist options
  • Save sukima/4683467 to your computer and use it in GitHub Desktop.
Save sukima/4683467 to your computer and use it in GitHub Desktop.

Super Simple Event Dispatcher

Use this to add events to your objects without needing any libaries.

Simple function can be imported or copy pasted. In your object constructor assign your event functions to the return value of the createCustomEvent().

Simple example:

<script src="createCustomEvent.js" type="text/javascript"></script>

Then in your object definition code:

// Define
function MyObject() {
  this.onCustomEvent = createCustomEvent();
}
MyObject.prototype.test = function() {
  this.onCustomEvent("message");
};

// Add listeners
var instance = new MyObject();
instance.onCustomEvent( function(msg) {
  alert(msg);
} );

// Run
instance.test();

See it working at jsbin.com.

global = exports ? @
global.createCustomEvent = ->
handlers = []
return ->
if arguments.length is 1 and typeof arguments[0] is "function"
handlers.push arguments[0]
return
handler.apply(@, arguments) for handler in handlers
return
(function(exports) {
exports.createCustomEvent = function() {
var handlers = [];
return function() {
if (arguments.length === 1 && typeof arguments[0] === 'function') {
handlers.push(arguments[0]);
return;
}
for (var i = 0, len = handlers.length; i < len; ++i) {
handlers[i].apply(this, arguments);
}
};
};
})(typeof exports !== "undefined" && exports !== null ? exports : this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment