Learn to Code via Tutorials on Repl.it!

← Back to all posts
"Event Listeners" for your JavaScript libraries
tussiez (574)

Custom "Event Listeners"

This tutorial is short and simple - but this problem stumped me for a while, so I decided to post it here in case anyone else has a similar issue.

Our custom event listeners will run a function on another script (the one using the library) when the library "fires" the event attached to the function.
To put it simply, this is a fancy way of calling functions.

To add "listeners", use the following code:

library.addEventListener('event-name',functionToDo);

On the library side, we simply set a variable to the function.

addEventListener: function(event,func){
this[event]=func;
}

Now, whenever we wish to fire an event, we run

this.someEvent(someData);

That's all there is to it!