Event Programming – Should an Event Listener Be Called if Attached After the Event?

event-programming

Should an event listener be called if it is attached after the event has already fired? What if the event will only be fired once?

The first example that comes to mind is the ready event in jQuery. The following snippet, when evaluated after the page has loaded, will still call the callback:

$(document).ready(function () {
    console.log("Works.");
});

The alternative to this behaviour could be a flag that is set when the page is loaded, forcing the consumer of the API to check to see if the event has already happened and act accordingly:

if (document.readyState == "complete") {
    console.log("Works.");
} else {
    $(document).ready(function () {
        console.log("Works.");
    });
}

While the above example is in the context of a web page loading where anything and everything (usually) needs to happen after the page has completely loaded, the same arguments could be made for any single component in an application, which has "singleton" events (load, start, end, etc). An example of a single component could be a map with a load event that fires to specify that the map that has loaded:

map.on("load", function () {
    console.log("The map has loaded.");
});

The above example comes from the ArcGIS API for JavaScript, where that event is fired only once, and if an a consumer "waits" for the map to load after the map is already loaded, the listener will never be called. The desired result requires checking the state of the map before the listener is attached:

if (map.loaded) {
    console.log("The map has loaded.");
} else {
    map.on("load", function () {
        console.log("The map has loaded.");
    });
}

Which behaviour is correct, requiring the consumer to check if an event has already fired or always calling the callback?

Best Answer

That depends upon whether it is really an Event or State Notification (which is what ready is). If it is an event, then you don't tell the listener about all prior events. If it is State Notification, then you tell them immediately after they have subscribed and you are in the specified state.

The tricky bit will be where it can be either a state or an event, depending upon how you look at it -- at worst, that is explained by the documentaion. At best you pick a good name that makes it clear which you mean.

Related Topic