Essentially, the idea is to be able to subscribe to a global events system based on criteria matching, rather than being DOM- or object-based.
Every event you can fire in the system consists of a subject (any JS object), a verb (a string indicating the action), and a hash that comprises additional specifiers (an object, if you will). You can listen on events based on matching criteria on any or all of the three; the only requirement is that you must specify a verb to listen to.
If you choose to listen on additional specifiers (
args below), your listener will only get called if it exactly matches all specifiers.
One further concept is that of priority. You can assign events with specific priorities if you’d like, but by default events will fire in an ordering determined by the number of
args that matched the criteria. The end result is that more specific listeners are fired first. For each
arg that matches, the priority of a listener is incremented by one. In the event of a tie, earlier-registered listeners are fired first.
The system lives under the kor.events namespace. There are three primary methods associated with it:
options here consists of five potential arguments:
subject: an object to listen to. Note that kor.events will add a
_kor_events_idkey to the object for performance reasons. (optional)
verb: a string representing the type of action that was performed. (required)
args: a hash containing additional specifiers about the event to listen on. (optional)
priority: gives an explicit priority to the listener. (optional)
callback: the function to call back to when a matching event fires. (required)
The callback will be given a single argument, which looks a lot like the
options hash, but will give all the criteria that the event firer specifies in relation to the event.
Returns a ticket ID you can use to unlisten to events later.
Looks much like the options given on
listen. The only difference is that a
callback and a
priority are not given.
When the callbacks of matching listeners are called, they can return
false to immediately halt any further event calls down the chain.
true if all events were called successfully (even if none matched);
false if some listener returned false and halted the chain.
Marks that the
subject is about to be eradicated. This does a couple of things:
- Fires an event with
subjectso that any listeners that are tracking the object can know to clean up after it.
- Removes the
subjectfrom kor.events internal tracking.
Removes a listener from the registry. This can be done if you can’t simply kill your callback function, and you need it to stop firing, or if you have a lot of events and worry about performance.
Returns the original event options hash that was passed in to register the event.
Clears everything from the registry.
As with everything I write, everything here is licensed under the WTFPL, but I request that you let me know what you think of it all.