2009-06-16 101 views
0

我重構了工作代碼以使用適當的對象,現在我無法使Prototype的AJAX.Request正常工作。代碼如下,它的工作在YUI的數據表的情況下:在原型中使用自己的AJAX請求回調方法

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回調但失敗。

問題是:我怎樣才能做到這一點?

回答

2

創建 「這種」 封閉:

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

試試這個:

onSuccess: this.setTableColumns.bind(this) 
+0

是'transport`變量仍然可用? – pstanton 2010-10-26 06:51:56

+0

是的,它是setTableColums的第一個參數。 – Sander 2011-10-26 14:24:27