Alex
Alex

Reputation: 1

I need to access event context AND object context in event handler

I've this piece of code:

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...
    };

}

As you can see the problem is when I call function sendUpdateRequest; how can I, at the same time, retrieve button infos and call a function?

Upvotes: 0

Views: 243

Answers (1)

jondavidjohn
jondavidjohn

Reputation: 62392

You might try this...

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...
    };

}

Because your using updateAction as a event handler, you correctly see that this will be the button that generates the event. Storing the initial context of the ActivityDialog will allow you to maintain access to it even within event handlers.

Upvotes: 1

Related Questions