Skip to content
Advertisement

Trying to wrap my head around custom events

I’m trying to get my head around custom events. I understand how to register and trigger custom events. However, it seems like its not possible to register truly custom events. Everything has to trace back to a DOM event like click, onload, blur, etc. Or am I wrong?

For example, suppose I have an array. I want to register an event that fires when the length of the array changes. To my understanding, I would have to register the event and then create a setInterval timer that checks the current array length against the previously stored length. If the length has changed, I would then need to trigger my custom event from inside the setInterval.

Is there a way to register an event for my array and have it fire automatically when the length changes?

Advertisement

Answer

Custom events are in the W3C spec, but none of the major browsers support them. This is why several other users have suggested 3rd party libraries. Prototype, YUI, JQuery, and most others have these capabilities. You can also roll your own.

If you’d like to see what some custom event syntax might look like, you can take a look at this tutorial for Prototype custom events. Some important points:

  • Prototype custom events must be attached to DOM elements, so that they can bubble like native events.
  • They must be in a prefix:event syntax in order to fire
  • They can contain a highly-useful memo parameter that allows any arbitrary context or set of objects to bubble with the event.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement