Lpc_dark Lpc_dark - 5 months ago 15
Javascript Question

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
}
}

Answer
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/

Comments