Question

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

Was it helpful?

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.

OTHER TIPS

Arrays do not have any sort of event notification system for changes in javascript. So, if you wanted to know when an array was changed, you would have to create your own notification system.

Since you don't want to use any frameworks (many of which offer event notification and triggering things), you would have to build your own.

There are several different approaches for event systems (messages through a generic message callback, individual callbacks for each event, object oriented approaches of either of these, etc...

The most straightforward (thought not necessarily the most elegant) is to have the object that creates the event maintain a list of callbacks for the event. Then, when an interested party wants to register for the event, they call a method and pass it the event and a callback. This is similar to how addEventListener works in the browser DOM for DOM events. The recipient of that method call, then stores the callback in an array of callbacks. Some time later when the actual event occurs, each callback that is registered for that event is called in turn.

Since array modifications don't trigger events by themselves, you would have to implement a function that both makes the array change and signals the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top