Javascript module pattern, ajax function callbacks

var ajaxStuff = (function () {

    var doAjaxStuff = function() {
      //an ajax call
    }

    return {
       doAjaxStuff : doAjaxStuff 
    }

})();

      

Can I use this pattern and get a response from a successful ajaxcall when my method is called? Something like that:

ajaxStuff.doAjaxStuff(successHandler(data){
    //data should contain the object fetched by ajax
});

      

I hope you understand this idea, otherwise I will explain.

+1


source to share


3 answers


Two things: 1. Add a parameter to the doAjaxStuff function. 2. When calling doAjaxStuff, pass an anonymous function (or function name)



var ajaxSuff = (function () {

var doAjaxStuff = function(callback) {
   // do ajax call, then:
   callback(dataFromAjaxCall);
}

return {
   doAjaxStuff : doAjaxStuff 
}

})();

// calling it:

ajaxStuff.doAjaxStuff(function(data){
    //data should contain the object fetched by ajax
});

      

+3


source


Just let's doAjaxStuff

accept the callback:

var doAjaxStuff = function(callback) {
    // an ajax call
    // Inside the Ajax success handler, call
    callback(response); // or whatever the variable name is
}

      



Depending on your general goals, you can also use deferred objects (or optional). This makes your code very modular. For example:

var doAjaxStuff = function() {
    // $.ajax is just an example, any Ajax related function returns a promise 
    // object. You can also create your own deferred object.
    return $.ajax({...});
}

// calling:

ajaxStuff.doAjaxStuff().done(function(data) {
    // ...
});

      

+1


source


I believe you need to read the jQuery docs for jQuery.ajax . You can make a call as simple as:

$.ajax('/path/to/file').success(function (data) {
    doStuff();
})

      

0


source







All Articles