1
var ajaxStuff = (function () {

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

    return {
       doAjaxStuff : doAjaxStuff 
    }

})();

Is there any way to make use of this pattern, and fetch the response from a successful ajaxcall when calling my method? Something like this:

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

Hope you get the idea, otherwise I'll elaborate.

Ken Redler
  • 23,863
  • 8
  • 57
  • 69
Johan
  • 35,120
  • 54
  • 178
  • 293

3 Answers3

3

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

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
});
Andre Loker
  • 8,368
  • 1
  • 23
  • 36
1

Just let doAjaxStuff accept a 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 overall goals, you could also use deferred objects instead (or in addition). This makes your code highly 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) {
    // ...
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

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

$.ajax('/path/to/file').success(function (data) {
    doStuff();
})
zzzzBov
  • 174,988
  • 54
  • 320
  • 367