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?

6
  • 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) Commented Feb 18, 2009 at 20:58
  • Ha! Good catch, totally missed that. Commented Feb 18, 2009 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. Commented Feb 18, 2009 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! Commented Feb 19, 2009 at 4: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. Commented Feb 19, 2009 at 16:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

'self' is already defined in the global scope. Using it as a name for a local variable is not recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.