1

构造函数需要一些时间,并且在调用方法时,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());
4

2 回答 2

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);
});
于 2013-10-19T13:55:46.470 回答
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);
于 2013-10-19T13:56:36.230 回答