Search code examples
jqueryajaxcallbackhookdeferred

jQuery Ajax Callback Hook System


When a button is clicked, an ajax call is made. The button provides a variable to be passed along with the ajax. When it's .done() and the data is returned, I want to be able to 'attach' or 'hook' any number of other functions (possibly in other files and possibly loaded before or after this ajax function) to access that returned data and do something with it. From what I've gathered so far, it's going to be a deferred/promise situation but I can't find the silver bullet solution anywhere (hopefully without using any timers).

 

page.html:

<button data-ajax_action="url/to/action">Button</button>

 

common.js:

$(document).on('click','[data-ajax_action]',function(e){

    var action = $(this).data('ajax_action');

    $.ajax({

        url: action,
        dataType: 'json'

    }).done(function(data){

        // do default stuff with data
        // somehow provide access to data var to other functions
    });

    e.preventDefault();
});

 

Now let's say I have another js file that's loaded before common.js that needs to 'hook into'/access that data after that ajax call is made. How would I set that up (to also let any number of other scripts to do the same)?


Solution

  • Like Barmar's answer but using a jQuery Callbacks object, which (from v1.7) is conceptually similar to an Array but with better control possibilities, specified with "flags".

    Assign a jQuery.Callbacks instance to a global ajax_callbacks variable :

    var ajax_callbacks = new jQuery.Callbacks( "once memory" );
    

    See the jQuery documentation for descriptions of the possible flags. "once memory" is a good start point.

    The other code can then do :

    ajax_callbacks.add(function(data) { /* do something with data */  });
    

    And in your .done() function you would do :

    ajax_callbacks.fire(data);