benoitr007 benoitr007 - 3 months ago 14
Javascript Question

Is there a name for the concept of attaching callbacks to a promise that acts as a global event that fires once? (like $(document).ready())

This may be an odd question, but I'm trying to name this concept in a comment:

var fonts = ['font1', 'font2'];
var font_loaded_deferreds = [];

fonts.each(function(n, font) {
var font_loaded_deferred = $.Deferred();
$.ajax({
// AJAX options to load the font here...
}).then(function(data) {
font_loaded_deferred.resolve();
});
font_loaded_deferreds.push(font_loaded_deferred);
});

var all_fonts_loaded_promise = $.when.apply($, font_loaded_deferreds);

var all_fonts_loaded = function(callback) {
all_fonts_loaded_promise.done(callback);
};


Usage:

all_fonts_loaded(function() {
// refresh stuff that depends on text size etc.
});


The idea here is to be able to attach any number of callbacks, anywhere in the code, to an "event" that fires once per page execution, a bit like jQuery's own $(document).ready()... particularly in the sense that if the "fonts loaded" event has already "fired" when the callback gets attached, the callback gets executed right away thanks to the promise. An event handler (with $.on() and $.trigger()) wouldn't execute at all if the binding happened after the event, so I feel like "event" is not the right word.

Of course, I realize that "no" is a perfectly valid answer to that question, but also feel free to discuss.

Answer

Is there a name for the concept of attaching callbacks to a promise that acts as a global event that fires once?

Not to my knowledge. However, that's exactly the behaviour promises are known for, so if you just say "promise" when asked for the concept then everyone will understand how it works.

And actually, not exposing that function which attaches "event" callbacks but instead just exposing the promise itself would simplify most code, and allow for chaining. At least change it to

function all_fonts_loaded(callback) {
    return all_fonts_loaded_promise.then(callback);
//  ^^^^^^                          ^^^^
}