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?

rmw
  • 1,253
  • 1
  • 12
  • 20
  • You want it to call itself every second? (since the call you setup with setTimeout has no arguments, and undefined == null, it will keep calling itself with the timeout) – some Feb 18 '09 at 20:58
  • Ha! Good catch, totally missed that. – Shog9 Feb 18 '09 at 21:04
  • in theory, yes it would call itself every second. in reality, i want to make sure that asp .net has completely loaded the page before i try to observe the click event. – rmw Feb 18 '09 at 21:26
  • But the code make no sense: If it's called without a parameter, or a parameter that has the primitive value of 'undefined' or 'null', it will keep calling itself until the end of the world: Since the call in the setTimeout has no parameter, the if-statement will NEVER be false. It makes no sense! – some Feb 19 '09 at 04:46
  • the purpose of the timeout is not to check if it was called without a parameter, it's to check that the button element has loaded and exists on the page. yes, this code would bomb if called without a parameter but it's not a multi-purpose API. – rmw Feb 19 '09 at 16:40
  • it's used in an ASP .net user control which will always call it with a parameter and if not the few developers using it will have to figure out why their code isn't working. it "makes no sense" to YOU because you don't know the context of the code or the development. – rmw Feb 19 '09 at 16:41

1 Answers1

2

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

Community
  • 1
  • 1
Shog9
  • 156,901
  • 35
  • 231
  • 235
  • 'self' is already defined in the global scope. Using it as a name for a local variable is not recommended. – some Feb 18 '09 at 20:55