Skip to content

Instantly share code, notes, and snippets.

@cosmomathieu
Last active August 7, 2019 12:59
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 cosmomathieu/4301b40c170e225dbfe00f99a66cf71c to your computer and use it in GitHub Desktop.
Save cosmomathieu/4301b40c170e225dbfe00f99a66cf71c to your computer and use it in GitHub Desktop.
An implementation of a JavaScript module with an event emitter/listener system
/**
* @see https://jsfiddle.net/cosmointeractive/ukb8Lpm1/
*/
const events = (function() {
'use strict'
var _triggers = {};
const on = function(event, callback) {
if (!_triggers[event]) {
_triggers[event] = [];
}
_triggers[event].push(callback);
return (this);
};
const triggerHandler = function(eventName) {
if (_triggers[eventName]) {
for (var i in _triggers[eventName]) {
_triggers[eventName][i]();
}
}
};
return {
on: on,
triggerHandler: triggerHandler
}
})();
var TheClass = (function(events) {
'use strict'
let _this = this;
var defaults = {
};
let bindEvents = function() {
module.on('eventCustom', function() {
alert('Event internal!');
});
}
let init = function(options) {
bindEvents();
return (this);
}
let module = $.extend({
init: init,
say: function() {
this.triggerHandler('eventCustom')
}
}, events)
return module;
})(events);
(function($) {
TheClass.init({})
.on('eventCustom', function() {
alert('Event external one');
})
.say();
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment