views:

441

answers:

4

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?

+2  A: 

why don't you write a method addElement for your array that you'll use whenever you want to insert elements,that way you will be able to write code in the event of array.length change. same thing with removeElement. Events are not meant to be used for this kind of thing.

xxxxxxx
That's one way to do it, but my example wasn't a specific problem I'm trying to solve, just an example to explain what I'm confused about.
Geuis
A: 

If you can use the third party Javascript library, then this can be useful.

Sachin Gaur
A: 

You ned to create the functions yourself or use a 3rd party library as suggested.

Very Versatile Electronic Document runs on a timer, making cutom events scalable.

novatv.stdios
+3  A: 

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.
Eric Nguyen