kael.shipman Posted November 29, 2007 Share Posted November 29, 2007 Hi again, This is another problem I've had for a while and haven't solved adequately: when I set a timeout or an interval from within an object and pass a reference to the object through "this" variable, the function loses it's reference after the first iteration. Likewise, when I attach an event through a function like addListener (shown below), the event also loses the object reference. My solutions involved setting a "self" local variable in each parent function, then using that instead of the "this" variable. However, in cases of setInterval or setTimeout, you have to then wrap that inside of an anonymous function to get it to work because the timing function loses the self variable after the first iteration. For example, this will work the FIRST time, but not after that: var myObject = function() { this.timeMe(); } myObject.prototype = { constructor : this, test : "test", timeMe : function() { var self = this; setInterval(self.tryMe, 1000); }, tryMe : function() { alert(this.test); } } while this will work: var myObject = function() { this.timeMe(); } myObject.prototype = { constructor : this, test : "test", timeMe : function() { var self = this; setInterval(function() { self.tryMe() }, 1000); }, tryMe : function() { alert(this.test); } } Here's the addListener function I was talking about. This is similar to the above examples. You have to pass it an anonymous function inside of which you call "self.myFunction()": function addListener(element, type, func, overwrite, bubbling) { if (typeof element == 'string') element = $(element); if (!element) return throwError('global::addListener - element not found'); bubbling = bubbling || false; overwrite = overwrite || false; if (overwrite) element['on'+type] = ''; if(window.addEventListener) { element.addEventListener(type, func, bubbling); return true; } else if(window.attachEvent) { element.attachEvent('on' + type, func); return true; } return throwError('global:addListener - couldn\'t attach event to element'); } myObject.prototype.addAnEvent = function() { var self = this; addListener('someElement', function() { self.tryMe(); }); } There's gotta be an easier way to juggle all these object references! Can anyone point me to some resources for explaining this stuff more clearly? Thanks, Kael Quote Link to comment Share on other sites More sharing options...
fenway Posted November 29, 2007 Share Posted November 29, 2007 This is another closure issue -- see if this helps. Quote Link to comment Share on other sites More sharing options...
fenway Posted December 19, 2007 Share Posted December 19, 2007 So are these: http://msdn2.microsoft.com/en-us/library/bb250448.aspx http://www.bazon.net/mishoo/articles.epl?art_id=824 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.