Skip to content

Instantly share code, notes, and snippets.

@Xananax
Last active January 25, 2018 01:16
Show Gist options
  • Save Xananax/ac4aeaa3dad084274f75e38fe9c2f80c to your computer and use it in GitHub Desktop.
Save Xananax/ac4aeaa3dad084274f75e38fe9c2f80c to your computer and use it in GitHub Desktop.
A very very simple yet functional event emitter, to try to understand and discuss how events work
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Event Dispatcher example</title>
</head>
<body>
</body>
<script>
/********************************
* SETUP - CREATING THE
* EVENT DISPATCHER
*******************************/
// creating an object
// I'm gonna call it eventDispatcher
// because it dispatches event
// and I lack imagination
const eventDispatcher = {
// this is an object containing the possible events
// each event type is an array. Each array
// will contain listeners; functions that trigger
// on events
listeners: {
click:[],
batata:[],
},
// this is a function used to add a listener
// it needs a valid event name ("click" or "batata")
// and a function to trigger
addEventListener: function(eventName,listenerFunction){
// adds the listener to the list of listeners
this.listeners[eventName].push(listenerFunction)
},
// this is a function to dispatch an event
// it needs a valid event name
// and accepts an optional argument to pass
// any type of data to the listeners
dispatchEvent: function(eventName,options){
// creates an event object
const event = {
type:eventName,
data:options
}
// we retrieve the correct list
const listenersList = this.listeners[eventName]
// we loop through all the listeners and trigger
// them one by one
for(var i = 0; i < listenersList.length; i++){
const currentListenerFunction = listenersList[i]
currentListenerFunction(event)
}
}
}
/********************************
* APP - USING THE
* EVENT DISPATCHER
*******************************/
// we add a listener to the 'click' event
eventDispatcher.addEventListener('click',function(options){
console.log('click was sent with the following options:',options)
})
// we add a listener to the 'batata' event
eventDispatcher.addEventListener('batata',function(options){
console.log('batata was sent, with the following options:',options)
})
// we trigger the 'batata' event every second
setInterval(function(){
eventDispatcher.dispatchEvent('batata')
},1000)
// we trigger the 'click' event when the page loads
eventDispatcher.dispatchEvent('click',{text:'this is optional'})
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment