2010-08-24 80 views
0

我是新來moootools和我創建一個模板類,這是我的代碼 -如何確定在mootools中完成請求的時間?

var Template = new Class({ 
    Singleton : true, 
    template : '', 

    /* gets the component type template */ 
    get : function(componentType){ 
    var tplUrl = Core.getUrl('backend') + 'response/' + componentType + '/get_template.php', 
     that = this, 
     request = new Request({url: tplUrl, method : 'get',onSuccess : function(responseText){ 
      that.template = responseText; 
      return that; 
     }}).send(); 
    } 

}); 

我想要做的是這樣的:

var tpl = new Template(); 
tpl.get('component').setTemplateData({name:'yosy'}); 

問題是,當我打電話這代碼:

var tpl = new Template(); 
console.log(tpl.get('component')); 

我沒有得到我當前的Template對象,我得到的是'undefined'。
我如何使這個可鏈接?

回答

1

正在製作的get函數內部的異步調用。該請求可能需要100ms,1s或10s,並且在get函數完成並返回時,請求仍將處於等待狀態。相反,您需要做的是,將回調函數傳遞給get並在成功時調用該函數。

get: function(componentType, successCallback) { 
    var request = new Request({ 
     .., 
     onSuccess: successCallback 
    }).send(); 
} 

請注意,您沒有從get函數返回任何東西。調用此方法的一個示例方法是:

tpl.get('component', function(responseText) { alert(responseText); }); 
+0

爲了使它可鏈接,他也可以變成一個同步請求,雖然它擊敗了目的:) – 2010-08-24 16:34:10

+0

我已經停止推薦同步選項:)但好的替代品將是[期貨和承諾]的這個概念(http:///en.wikipedia.org/wiki/Futures_and_promises)以及Dustin Diaz的[async method queues](http://www.dustindiaz.com/async-method-queues/)。 – Anurag 2010-08-24 16:51:45

-1

您的get函數缺少返回值。如果你想函數鏈應返回對象本身:

get : function(componentType){ 
var tplUrl = Core.getUrl('backend') + 'response/' + componentType + '/get_template.php', 
    that = this, 
    request = new Request({url: tplUrl, method : 'get',onSuccess : function(responseText){ 
     that.template = responseText; 
     return that; 
    }}).send(); 

    return this; 
} 
+0

'return request;' – 2010-08-24 15:02:53

+0

不確定返回當前對象或請求是否在此處有任何幫助。 'get'可能需要回調組件加載時的回調。 – Anurag 2010-08-24 15:41:52

+0

但我想在加載請求時返回對象。 – Yosi 2010-08-24 15:47:51

相關問題