我重构了工作代码以使用正确的对象,现在我无法让Prototype的AJAX.Request正常工作。代码如下,它在YUI的DataTable上下文中工作:

SearchTable.prototype.setTableColumns = function (transport) {
      this.dataTableColumns = transport.responseText.evalJSON();
      this.dataTableCallback();
};

SearchTable.prototype.setTableConfiguration = function (transport) {
  this.dataTableConfiguration = transport.responseText.evalJSON();
  this.dataTableCallback();
};

SearchTable.prototype.show = function () {
  ....
  new Ajax.Request(this.dataProxy, {
    method: 'get',
    parameters: {
      format: 'json',
      param: 'columns'
    },
    onSuccess: this.setTableColumns
  });

 new Ajax.Request(this.dataProxy, {
   method: 'get',
   parameters: {
     format: 'json',
     param: 'configuration'
   },
   onSuccess: this.setTableConfiguration
  });
}
};

 SearchTable.prototype.dataTableCallback = function () {
        ....
 }

我的问题是永远不会调用 dataTableCallback 。显然它抛出了 this 未定义的异常,我可以理解:在对象上下文中没有调用回调,因此从未分配 this 。我试过curryfying回调但失败了。

问题是:我怎样才能使这项工作成功?

有帮助吗?

解决方案

为“this”创建一个闭包:

SearchTable.prototype.show = function () {
  ....

  var self = this;

  new Ajax.Request(this.dataProxy, {
    method: 'get',
    parameters: {
      format: 'json',
      param: 'columns'
    },
    onSuccess: function(transport) { self.setTableColumns(transport); }
  });

其他提示

试试这个:

onSuccess: this.setTableColumns.bind(this)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top