Jump to content

requestAnimationFrame loses scope


xdiepx
 Share

Recommended Posts

When I do a requestAnimationFrame it loops through once then it loses its scope. At the moment i don't want to use the arrow function because IE 11 doesn't support it (ref http://caniuse.com/#feat=arrow-functions). Does anyone know a way around this. Here is a sample code

(function(){

var main =function(){
this.init();
}

var p = main.prototype;

p.init = function(){

this.stage = new PIXI.Container();
this.renderer = new PIXI.autoDetectRenderer(1024,768,{id:"stage"});
document.body.appendChild(this.renderer.view);

this.updateStage();

}

p.updateStage= function(){
requestAnimationFrame(this.updateStage);
this.renderer.render(this.stage);
}

}())

As soon as it tries to render it calls this.renderer becomes undefined. 

I have tried binding the requestAnimationFrame which didn't work. So i console.log it out. the first time it logs i get main property with the correct property such as main.stage, main.renderer. The second time it returns me Window (in chrome). I am wondering if anyone knows how to keep the scope.

Link to comment
Share on other sites

You could also do this:

requestAnimationFrame(this.update.bind(this))

But don't, bind isn't cheap and you won't get any engine optimisations as it'll count as a new function each tick rather than a hot-path op. Do it the way @Fatalist suggests.

Thankfully IE11 will be put out to graze, Edge seems to be keeping fairly good parity and stability with proper browsers now so hopefully you won't have the compat issue for long, but, until that day there is always transpilation. Babel is the standard, but there are others out there too. The standard transpile for most arrow/lambda functions is to use the `var this = that` hack, which is fine for transpilers, but don't write that yourself, prefer .bind to scope functions (also, try not to do it too often).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...