javascript - 延迟一个原型(prototype)函数

标签 javascript jquery

假设我在 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/

相关文章:

javascript - jQuery 的 attr() 和 getAttribute() 之间的区别

javascript - XML3D:生成Ray

javascript 父问题

javascript - 两个 UL 已链接,单击 LI 并在两个 UL 中将 active 添加到 LI

javascript - 在 Javascript 中生成内容时应该使用字符串还是节点?

javascript - 在 Jquery 中读取分配给 Data- 的数组时出错。我正在使用 .data()

javascript - 从 JQuery 切换到 RightJS

javascript - 仅在<选择多个>中选中

javascript - 应用固定位置时的过渡 div

javascript - Node.js Express 网站实时更新数据