views:

200

answers:

1

I'm new to object oriented javascript. I have a set up method that I want to a) check if an element is null and if so wait and call itself again and b) observe the click event of a button.

ErrorBox.prototype.setUpErrorBox = function(btnClientID) {
    if (btnClientID == null) {
        setTimeout("setUpErrorBox()", 1000)
        return;
    }
    Event.observe(btnClientID, 'click', setValSummary);
}

I'm getting errors that setUpErrorBox and setValSummary don't exist (which they don't). How can I reference them? I tried this.setValSummary which didn't work.

In other words, how do I call the equivalent of a class's method from another method of the same class in javascript?

+2  A: 

Use closures to hold on to your execution context:

ErrorBox.prototype.setUpErrorBox = function(btnClientID) 
{
   var box = this; // object context reference
   if (btnClientID == null) 
   {
      // use closure as event handler to maintain context
      setTimeout(function() { box.setUpErrorBox() }, 1000)
      return;
   }
   // again, use closure as event handler to maintain context
   Event.observe(btnClientID, 'click', function() { box.setValSummary() });
}

See also: JavaScript Callback Scope

Shog9
'self' is already defined in the global scope. Using it as a name for a local variable is not recommended.
some
Fair enough - changed it.
Shog9
worked perfectly. thanks.
bmwbzz