I have a method that is a big setInterval statement, and it needs access to the this object of the object that owns the method from inside the interval. I implemented a simple closure, but it doesn't seem very elegant:
connect: function(to, rate, callback){
var cthis = this, //set cthis to this,
connectIntervalID = setInterval(function(){
if(cthis.attemptConnect(to)){ //reference it here,
clearInterval(connectIntervalID)
cthis.startListening(10) //here,
callback && callback.apply(cthis, []) //and here
}
}, rate)
}
You could also do it with apply or call, if you wanted to use this instead of cthis
connect: function(to, rate, callback){
var cthis = this,
tempFunc = function(){
if(this.attemptConnect(to)){
clearInterval(connectIntervalID)
this.startListening(10)
callback && callback.apply(this, [])
}
}�
connectIntervalID = setInterval(function(){tempFunc.apply(cthis, [])}, rate)
}
However, that seems even worse...
Using a .bind makes it a bit better (in my opinion, you may or may not agree):
support code:
function $A(args){
var out = [];
for(var i=0, l=args.length; i<l; i++){ out.push(args[i]); }
return out;
}
Function.prototype.bind = function() {
var __method = this, args = $A(arguments), object = args.shift();
return function() {
return __method.apply(object || this, args.concat( $A(arguments) ));
};
};
and your code becomes:
connect: function(to, rate, callback){
connectIntervalID = setInterval((function(){
if(this.attemptConnect(to)){ //reference it here,
clearInterval(connectIntervalID)
this.startListening(10) //here,
callback && callback.apply(this, []) //and here
}
}).bind(this), rate)
}
But I'm afraid you won't get a whole lot better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With