2011-12-22 107 views
0

我有這段代碼:我需要訪問事件上下文和對象範圍內的事件處理程序

function ActivityDialog(_divId, _title) { 

    function addButton() { 
     var buttonElement = document.createElement('input'); 
     buttonElement.setAttribute('type','button'); 
     buttonElement.setAttribute('class','button'); 
     buttonElement.setAttribute('id','updateButton-' + id);); 
     buttonElement.onclick = this.updateAction; 
    }; 

    function updateAction() { 
     var buttonId = this.id; // correct: this is the Button 
     this.sendUpdateRequest(stringUrl); // not defined: Need to reference the current ActivityDialog!!!  
    }; 

    function sendUpdateRequest(url) { 
     // something... 
    }; 

} 

正如你所看到的問題是,當我打電話功能sendUpdateRequest;哪能,在同一時間,檢索按鈕信息並調用函數?

+0

http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript我希望這篇文章能幫到 – 2011-12-22 15:39:28

+1

我不明白這個問題。 – 2011-12-22 15:45:17

+0

@ TomalakGeret'kal他有一個範圍問題,他試圖在事件處理程序中用'this'(Button)和Object context(ActivityDialog)引用事件上下文。 – jondavidjohn 2011-12-22 16:34:28

回答

1

你可以試試這個...

function ActivityDialog(_divId, _title) { 

    // Store the ActivityDialog context 
    var self = this; 

    function addButton() { 
     var buttonElement = document.createElement('input'); 
     buttonElement.setAttribute('type','button'); 
     buttonElement.setAttribute('class','button'); 
     buttonElement.setAttribute('id','updateButton-' + id);); 
     buttonElement.onclick = this.updateAction; 
    }; 

    function updateAction() { 
     var buttonId = this.id; 
     self.sendUpdateRequest(stringUrl); // <--------------------- 
    }; 

    function sendUpdateRequest(url) { 
     // something... 
    }; 

} 

因爲你使用updateAction作爲事件處理程序,正確地看到this將生成事件的按鈕。存儲ActivityDialog的初始上下文將允許您保持對事件處理程序的訪問權限。

+0

不幸的是,我已經有這個問題:sendUpdateRequest沒有定義。 stringurl是正確的價值(我使用螢火蟲進行調試)。按鈕創建發生在對象ActivityDialog中定義的函數中。我需要引用另一個ActivityDialog函數sendUpdareRequest .. – Alex 2011-12-22 15:41:06

+0

@Alex更新回答 – jondavidjohn 2011-12-22 15:52:49

相關問題