How to use requestAnimationFrame with a TypeScript object? How to use requestAnimationFrame with a TypeScript object? typescript typescript

How to use requestAnimationFrame with a TypeScript object?


You've lost this context. Two possible fixes:

class Contoso{   /* ... */   // Use () => syntax so Render always gets 'this' context   // from the class instance   Render = () => {      //...snip doing any actual drawing for the purpose of this question      requestAnimationFrame(this.Render);   }}

The alternate fix is probably slightly clearer, but has the downside of making a lot more allocations (you probably don't want to allocate 1 closure per frame!)

   Render() {      //...snip doing any actual drawing for the purpose of this question      requestAnimationFrame(() => this.Render);   }


Use arrow syntax (lambda):

requestAnimationFrame(() => this.Render());


On Firefox 49.0.1 I've got an error message using Ryan Cavanaugh solution.

SyntaxError: bad method definition

for the line :

Render = ()=> {

The work around I've found looks like this :

class Test{    constructor(){        this.Render = ()=> {            requestAnimationFrame( this.Render );        };    }}