Javascript模块模式,ajax函数回调 [英] Javascript module pattern, ajax functions callbacks

查看:85
本文介绍了Javascript模块模式,ajax函数回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var ajaxStuff = (function () {

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

    return {
       doAjaxStuff : doAjaxStuff 
    }

})();

有什么方法可以利用这种模式,并在调用我的方法时从成功的ajaxcall中获取响应?像这样:

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.

推荐答案

两件事: 1.将参数添加到doAjaxStuff函数. 2.调用doAjaxStuff时,传入一个匿名函数(或函数名称)

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
});

这篇关于Javascript模块模式,ajax函数回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆