Javascript this object inside intervals/timeouts -
i have method big setinterval statement, , needs access this object of object owns method inside interval. implemented simple closure, doesn't seem elegant:
connect: function(to, rate, callback){ var cthis = this, //set cthis this, connectintervalid = setinterval(function(){ if(cthis.attemptconnect(to)){ //reference here, clearinterval(connectintervalid) cthis.startlistening(10) //here, callback && callback.apply(cthis, []) //and here } }, rate) } you apply or call, if wanted 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, seems worse...
using .bind makes bit better (in opinion, 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 code becomes:
connect: function(to, rate, callback){ connectintervalid = setinterval((function(){ if(this.attemptconnect(to)){ //reference here, clearinterval(connectintervalid) this.startlistening(10) //here, callback && callback.apply(this, []) //and here } }).bind(this), rate) } but i'm afraid won't whole lot better.
Comments
Post a Comment