构造函数需要一些时间,并且在调用方法时,尚未定义this.folders
。如何允许getIt()
等到构造函数完成?
function test() {
var t=this;
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
t.folders=returned;
});
}
test.prototype.getIt = function() {
return this.folders;
};
var myObj = new test();
console.log(myObj.getIt());
答案 0 :(得分:2)
由于$.getJSON()
是异步的,因此在填充test()
后无法预先t.folders
返回。
您可以使用回调:
function test(callback) {
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
callback(returned);
});
}
var myObj = new test(function (folders) {
console.log(folders);
});
或承诺(在此示例中,使用Q库):
function test() {
var t = this;
t.folders = Q.defer();
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
t.folders.resolve(returned);
});
}
test.prototype.getIt = function() {
return this.folders.promise;
};
var myObj = new test();
myObj.getIt().done(function (folders) {
console.log(folders);
});
答案 1 :(得分:1)
该调用是异步的,因此您应该显示一个加载微调器,然后通过填充您收到的数据将其删除。
function test() {
var t=this;
//show loading spinner
$.getJSON('~.php?task=getFolders&dummy='+new Date().getTime(), function(returned){
t.folders=returned;
//hide loading spinner
//add data to document
});
}
test.prototype.getIt = function() {
return this.folders;
};
var myObj = new test();
console.log(myObj.getIt());
如果您希望在某些时候初始化某些内容后运行代码而不包括回调,即在您的ajax请求中,则一个跨浏览器解决方案将不断检查,如下面的代码所示,
function runCode(selector,theMethod,timeInMillis){
if($(selector).length>0){
theMethod();
}else{
setTimeout(function(){runCode(selector,theMethod,timeInMillis);},timeInMillis);
}
}
runCode('.the-class-of-data',function(){
console.log(myObj.getIt());
},100);