Question

I have refactored working code to use proper objects and now I can't get Prototype's AJAX.Request to work properly. The code is below, it's working in context of YUI's 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 () {
        ....
 }

My problem is that dataTableCallback is never called. Apparently it is throwing an exception that this is undefined, which I can understand: callbacks are not called in object context and thus this is never assigned. I've tried curryfying callbacks but failed.

The question is: how can I manage to make this work?

Was it helpful?

Solution

Create a closure for "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); }
  });

OTHER TIPS

Try this:

onSuccess: this.setTableColumns.bind(this)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top