cnwerb Posted December 12, 2016 Share Posted December 12, 2016 I'm trying to start a game loop in my PixiJS app but I'm getting an annoying error, the function loses scope after the first loop. Here's my code to make it clear: (take note of the console.log statements) import { Component, OnInit } from '@angular/core'; declare var PIXI: any; declare var $: any; @Component({ selector: 'pixi-component', templateUrl: './pixi.component.html', styleUrls: ['./pixi.component.css'] }) export class PixiComponent implements OnInit { private renderer; private stage; constructor() {} ngOnInit() { this.generatePixiCanvas(); } generatePixiCanvas() { this.create(this.getParentDivWidth(), this.getParentDivHeight()); this.stage = new PIXI.Container(); this.loop.bind(this); this.loop(); this.renderer.render(this.stage); } getParentDivHeight() { return $('#canvas').height(); } getParentDivWidth() { return $('#canvas').width(); } create(width: number, height: number, scale: boolean = false){ if (this.renderer) return this; this.renderer = PIXI.autoDetectRenderer(this.width, this.height); document.getElementById('pixi-canvas-container').appendChild(this.renderer.view); console.log("we got here"); return this; } loop = function(){ requestAnimationFrame(this.loop); console.log("loop"); } } So when I run this code, I get the following output on the browser console: "we got here" "loop" "EXCEPTION: Cannot read loop property of undefined" So it seems to me that the "this" object is losing scope after the first call of the loop() function. How can I keep the scope? You can see I tried this.loop.bind(this) but it doesn't work Quote Link to comment Share on other sites More sharing options...
cnwerb Posted December 12, 2016 Author Share Posted December 12, 2016 Fixed using arrow functions. In case anyone was wondering: loop = function(){ //Arrow functions preserve scope... requestAnimationFrame(() => { this.loop() } ); this.renderer.render(this.stage); console.log("loop"); } 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.
Note: Your post will require moderator approval before it will be visible.