Usando métodos de devolución de llamada propios para solicitud AJAX en Prototype
-
05-07-2019 - |
Pregunta
He refactorizado el código de trabajo para usar objetos adecuados y ahora no puedo hacer que AJAX.Request de Prototype funcione correctamente. El código está abajo, está trabajando en el contexto de la tabla de datos de 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 () {
....
}
Mi problema es que dataTableCallback
nunca se llama. Aparentemente, es una excepción que this
no esté definido, lo que puedo entender: las devoluciones de llamada no se llaman en el contexto del objeto y, por lo tanto, this
nunca se asigna. He intentado curryfying devoluciones de llamada pero fallé.
La pregunta es: ¿cómo puedo lograr que esto funcione?
Solución
Crear un cierre para " este " ;:
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); }
});
Otros consejos
Prueba esto:
onSuccess: this.setTableColumns.bind(this)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow