Question

I see that I can dispatch a custom event to an object.

  1. I'm wondering why a custom event needs to be dispatched to an object at all.

  2. I want to trigger an event at a set interval, and after reading documentation on custom events, I still haven't figured out how to trigger them with functions. How is it done?

For example, I want to use setInterval() to trigger my custom event 'nextTime' every 30 seconds.

Était-ce utile?

La solution

dispatching events is the same as triggering them, and as they are custom events, they would never be naturally triggered by anything, so you have to trigger them yourself. To trigger an event from an interval just dispatch the event inside the interval.

The reason you need an object is because it's an event handler, if it wasn't attach to an element, you wouldn't really need an event handler, you could just use regular functions instead.

var event = new Event('custom'),
    elem  = document.getElementById('test');

elem.addEventListener('custom', function (e) {
    console.log('custom triggered');
}, false);

setInterval(function() {
    elem.dispatchEvent(event);
}, 30000);

FIDDLE

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top