2011-12-22 114 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

相关问题