如何确定何时在Mootools中完成的请求?
-
30-09-2019 - |
题
我是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') );
我没有得到当前的模板对象,我得到的是“未定义”。
我如何使这个链子?
解决方案
您正在在内部进行异步电话 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); });
其他提示
您的获取功能缺少返回值。如果要链接函数,则应返回对象本身:
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