views:

614

answers:

2

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 following, 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 exceptioin 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?

+3  A: 

Try this:

onSuccess: this.setTableColumns.bind(this)
Alsciende
is the `transport` variable still available?
pstanton
+2  A: 

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); }
  });
Greg
Thanks, assigning `this` to something else was the key.
rassie
Still, a combination of both your and Cédric's solution is the best.
rassie
Still, I think that you don't have to assign this to something else in this example. Since setTableColumn is called as a method of *this*, *this* is set in its body. That's the same thing as using bind(), but a bit less prototype-ish :)
Alsciende
I'm so stupid sometimes. Sorry for the previous comment Greg, it was dumb.
Ionuț G. Stan