Last active
May 22, 2018 09:11
-
-
Save svarunan/a47be86e29184ef316713605addb1ec6 to your computer and use it in GitHub Desktop.
Simple event emitter for Javascript Constructor
This file contains 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 customEvent = function(){ | |
var self =this; | |
self.events = {} | |
self.on = function (event, listener) { | |
if (typeof self.events[event] !== 'object') { | |
self.events[event] = [] | |
} | |
self.events[event].push(listener) | |
} | |
self.removeListener = function (event, listener) { | |
let idx | |
if (typeof self.events[event] === 'object') { | |
idx = self.events[event].indexOf(listener) | |
if (idx > -1) { | |
self.events[event].splice(idx, 1) | |
} | |
} | |
} | |
self.emit = function (event) { | |
var i, listeners, length, args = [].slice.call(arguments, 1); | |
if (typeof self.events[event] === 'object') { | |
listeners = self.events[event].slice() | |
length = listeners.length | |
for (i = 0; i < length; i++) { | |
listeners[i].apply(self, args) | |
} | |
} | |
} | |
self.once = function (event, listener) { | |
self.on(event, function g () { | |
self.removeListener(event, g) | |
listener.apply(self, arguments) | |
}) | |
} | |
} | |
/* | |
var Parent = function(){ | |
this.channel = new customEvent(); | |
// rest of you logic | |
} | |
var myParent = new Parent(); | |
myParent.channel.on("alarm", function(data){ | |
console.log("Alarm: ",data); | |
}); | |
myParent.channel.emit("alarm",{type:"fire"}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment