Domanda

Ho eseguito il refactoring del codice di lavoro per utilizzare oggetti adeguati e ora non riesco a far funzionare correttamente AJAX di Prototype. Il codice è sotto, funziona nel contesto della DataTable di YUI:

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 () {
        ....
 }

Il mio problema è che dataTableCallback non viene mai chiamato. Apparentemente è un'eccezione che this non sia definito, cosa che posso capire: i callback non vengono chiamati nel contesto dell'oggetto e quindi this non viene mai assegnato. Ho provato a richiamare curry ma non ci sono riuscito.

La domanda è: come posso riuscire a farlo funzionare?

È stato utile?

Soluzione

Crea una chiusura per " questo " ;:

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); }
  });

Altri suggerimenti

Prova questo:

onSuccess: this.setTableColumns.bind(this)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top