我重构了工作代码以使用正确的对象,现在我无法让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
。我试过curryfying回调但失败了。
问题是:我怎样才能使这项工作成功?
答案 0 :(得分:4)
试试这个:
onSuccess: this.setTableColumns.bind(this)
答案 1 :(得分:2)
为“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); }
});