Archive for the ‘timer’ Tag
The cat ate my Scope
If you are one of these JavaScript developers who likes to use an Object Oriented approach, using JavaScript constructors, I’m sure you have had a lot of headaches when you have tried to call some object’s method from setInterval() or setTimer() JavaScript functions. The problem is that when your method is called, it is called from the window object scope, losing your object’s one.
To avoid this problem we will introduce a solution in two steps, the first is to obtain a reference to your object instance, which is enough for some needs, and the second is to call your method from the object’s scope, which is needed to access the private part of your object. Here we go:
1. Remember that in JavaScript functions can have properties too, so you can save your object instance in a property of your favourite method and then access this property trought arguments.callee object which is a reference to the current function. See the following example:
var MyObject = function(){
this._periodicMethod = function(){
var objectInstance = arguments.callee._scope;
//Do the timed action over the objectInstance..
}
this._publicMethod._scope = this;
//Set the timer
window.setInterval(this._publicMethod,10000); //Call the method every 10 seconds.
}
2. Using this method you have obtained a reference to your object, so you can already access its public interface. That could be enough for some uses, but sometimes we need to update private parts of our objects, so we actually need to operate from within the object. To ensure your method is working with the correct scope you can add the following check to your method code:
if(this != arguments.callee._scope){
return arguments.callee.apply(arguments.callee._scope,arguments);
}
//Do the private stuff…
}
Take care with this last method, as it won’t work with older navigators (IE 5.0 or less) whose don’t support the apply method. You can see other techniques to recover your scope in this blog, but this one is the fastest and easier.
Leave a Comment