我已经重构了工作代码以使用适当的对象,现在我无法获得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
。我试过咖喱回调,但失败了。问题是:我如何设法使它起作用?
最佳答案
为“ 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); }
});