我需要在事件处理程序中访问事件上下文和对象上下文

时间:2011-12-22 15:30:42

标签: javascript events scope this

我有这段代码:

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;时,如何同时检索按钮信息并调用函数?

1 个答案:

答案 0 :(得分: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的初始上下文将允许您甚至在事件处理程序中维护对它的访问。

相关问题