• Categories

  • Stackable

    ** this is still a draft **

    Stackable is a small library to handle multiple callbacks for your event based environment.
    Basically it allows to chain, at run time, any number of synchronous or asynchronous functions and use it like a normal synchronous function (or asynchronous with the Deferred/Promise pattern).

    Here some example:

    var callback = $function(
      function(arg) {
        console.log('Function n.1',arg);
        },
      function(arg) {
        console.log('Function n.2',arg);
        });
      );

    // functions will be called in the same order they are defined
    callback.call(my_context,'my param');
    // will produce output:
    // Function n.1 'my param'
    // Function n.2 'my param'

    // Or even better you could use the Defferred/Promise pattern
    $.when(callback.promise('my param'))
      .done(function() {
        console.log('Finished!');
        // will produce output:
        // Function n.1 'my param'
        // Function n.2 'my param'
        // Finished!
        });

    Suppose now you want to add an asynchronous function to the stack, just use the push() method to enqueu it, like a normal array.
    Here is useful the Deferred/Promise pattern: if at some point you need to add an asynchronous function, you don’t need to change anything in the part of the code that calls the callback function:

    callback.push(function() {
      setTimeout(function(arg) {
        console.log('Function n.3',arg);
        },1000);
      });
     
    // below doesn't change
    $.when(callback.promise('my param'))
      .done(function() {
        console.log('Finished!');
        // will produce output:
        // Function n.1 'my param'
        // Function n.2 'my param'
        // Function n.3 'my param'
        // Finished!
        });

    More

    More about Stackable