2012-02-28 195 views
1
var ajaxStuff = (function() { 

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

    return { 
     doAjaxStuff : doAjaxStuff 
    } 

})(); 

有什麼辦法來使用這種模式,並從調用我的方法時成功的ajaxcall獲取響應?就像這樣:Javascript模塊模式,ajax函數回調

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

希望你明白,否則我會詳細說明。

+0

爲什麼不只是'.ajax('url')。success(function(data){...});'? – zzzzBov 2012-02-28 22:05:13

回答

3

兩件事情: 1.參數添加到doAjaxStuff功能。 2.當調用doAjaxStuff,傳入一個匿名函數(或函數的名稱)

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

就讓doAjaxStuff接受回調:

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

根據您的總體目標,你也可以使用deferred objects代替(或補充)。這使得你的代碼高度模塊化。例如:

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) { 
    // ... 
}); 
0

我認爲你需要閱讀jQuery的文檔的jQuery.ajax。你可以打一個簡單的電話:

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