假设我在 JS 中创建类
function UnitTable(options){
this.name = options.name;
}
UnitTable.prototype = {
query : function(){
$.post('php.php', { func : "get" }, function(data){
if (data) this.data = data;
});
return this;
},
append : function(){
$('#result').append(this.data);
}
}
var unitTable = new UnitTable(options).query().append();
问题是异步的 AJAX 调用不会在调用追加之前完成。
我尝试使用 $.Deferred() 但似乎无法正确返回它(例如 reutrn deferred.promise())并继续链式事件。
最佳答案
你不能那样做,但你可以在query
中设置一个promise值,并在append
中处理回调:
UnitTable.prototype = {
query: function() {
this.queryPromise = $.post('php.php', {func: "get"});
return this;
},
append: function() {
this.queryPromise.done(function(data) {
$('#result').append(data);
});
return this;
}
};
new UnitTable(options).query().append();
关于javascript - 延迟一个原型(prototype)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26187427/