Search code examples
javascriptcustom-event

How does one create a custom event in javascript that watches an array?


I see other questions for how to create custom events, but I'm not clear on how to track specific custom conditions.

In my example, I need to "listen" for the eventuality that an array has gone from having x elements to y elements.

I'm not sure if it's a good idea to prototype on top of Array, though that's kind of ideally what I need.

However, the broader question is, what's the methodology for writing custom listeners that are effectively the analog of -pseudo-

onClockStruckTwo or onDomChanged or onRapture

Meaning, that rather than waiting for some other predefined onEvent (onclick, onkeydown, etc) to happen, I want to make my own.

And please no Framework answers. I'm trying to understand how this actually works in native javascript.

TIA


Solution

  • The question I ask you is "what are you listening from?" If you're listening to a change on the server you could setTimeout an AJAX call, but that'd be far from suggested. If you're strictly looking to have the length of an element change, then there must be something else that you can know will set off the event. I say if it's not server related, don't "listen" at all, just attach the desired Javascript code to the end of something that you know will trigger the event change.

    EDIT

    Here's a list of all the Javascript event types. I don't see any mentions of an DOM object being empty. You may SOL with the way your hoping to do it.