mootoolsでリクエストがいつ完了したかを確認するにはどうすればよいですか?
-
30-09-2019 - |
質問
私はmoootoolsを初めて使用し、テンプレートクラスを作成しています。これは私のコードです -
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 オブジェクトを取得できません。「未定義」です。
これをチェーン可能にするにはどうすればよいですか?
解決
内部で非同期呼び出しを行っています。 get
関数。リクエストには 100 ミリ秒、1 秒、または 10 秒かかる場合があり、その時点で get
関数が終了して戻りますが、リクエストはまだ保留中です。代わりに、コールバック関数を渡す必要があります。 get
そしてそれを成功と呼びます。
get: function(componentType, successCallback) {
var request = new Request({
..,
onSuccess: successCallback
}).send();
}
get 関数からは何も返されないことに注意してください。これを呼び出す方法の 1 つの例は次のとおりです。
tpl.get('component', function(responseText) { alert(responseText); });
他のヒント
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;
}
所属していません StackOverflow