Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript custom Event Listener

I was wondering if anyone can help me understand how exactly to create different Custom event listeners.

I don't have a specific case of an event but I want to learn just in general how it is done, so I can apply it where it is needed.

What I was looking to do, just incase some folks might need to know, was:

var position = 0;  for(var i = 0; i < 10; i++) {     position++;     if((position + 1) % 4 == 0)     {         // do some functions     } } 
like image 977
Lpc_dark Avatar asked Mar 12 '12 17:03

Lpc_dark


People also ask

How do I listen to custom events?

To listen for the custom event, add an event listener to the element you want to listen on, just as you would with native DOM events. document. querySelector("#someElement"). addEventListener("myevent", (event) => { console.

What is Javascript CustomEvent?

Adding custom data – CustomEvent()To add more data to the event object, the CustomEvent interface exists and the detail property can be used to pass custom data. For example, the event could be created as follows: const event = new CustomEvent('build', { detail: elem.

What is CustomEvent?

The CustomEvent interface represents events initialized by an application for any purpose. Note: This feature is available in Web Workers.


2 Answers

var evt = document.createEvent("Event"); evt.initEvent("myEvent",true,true);  // custom param evt.foo = "bar";  //register document.addEventListener("myEvent",myEventHandler,false);  //invoke document.dispatchEvent(evt); 

Here is the way to do it more locally, pinpointing listeners and publishers: http://www.kaizou.org/2010/03/generating-custom-javascript-events/

like image 101
Max Avatar answered Sep 23 '22 06:09

Max


Implementing custom events is not hard. You can implement it in many ways. Lately I'm doing it like this:

/*************************************************************** * *   Observable * ***************************************************************/ var Observable; (Observable = function() { }).prototype = {     listen: function(type, method, scope, context) {         var listeners, handlers;         if (!(listeners = this.listeners)) {             listeners = this.listeners = {};         }         if (!(handlers = listeners[type])){             handlers = listeners[type] = [];         }         scope = (scope ? scope : window);         handlers.push({             method: method,             scope: scope,             context: (context ? context : scope)         });     },     fireEvent: function(type, data, context) {         var listeners, handlers, i, n, handler, scope;         if (!(listeners = this.listeners)) {             return;         }         if (!(handlers = listeners[type])){             return;         }         for (i = 0, n = handlers.length; i < n; i++){             handler = handlers[i];             if (typeof(context)!=="undefined" && context !== handler.context) continue;             if (handler.method.call(                 handler.scope, this, type, data             )===false) {                 return false;             }         }         return true;     } }; 

The Observable object can be reused and applied by whatever constructor needs it simply by mixng the prototype of Observable with the protoype of that constructor.

To start listening, you have to register yourself to the observable object, like so:

var obs = new Observable(); obs.listen("myEvent", function(observable, eventType, data){     //handle myEvent }); 

Or if your listener is a method of an object, like so:

obs.listen("myEvent", listener.handler, listener); 

Where listener is an instance of an object, which implements the method "handler".

The Observable object can now call its fireEvent method whenever something happens that it wants to communicate to its listeners:

this.fireEvent("myEvent", data); 

Where data is some data that the listeners my find interesting. Whatever you put in there is up to you - you know best what your custom event is made up of.

The fireEvent method simply goes through all the listeners that were registered for "myEvent", and calls the registered function. If the function returns false, then that is taken to mean that the event is canceled, and the observable will not call the other listeners. As a result the entire fireEvent method will return fasle too so the observable knows that whatever action it was notifying its listeners of should now be rolled back.

Perhaps this solution doesn't suit everybody, but I;ve had much benefit from this relatively simple piece of code.

like image 36
Roland Bouman Avatar answered Sep 22 '22 06:09

Roland Bouman