Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Call in Javascript Class (requestanimationframe)

I have a simple class that I am using to manage scenes in three.js. I am having issues with the requestAnimationFrame loop finding the function reference. I know I am missing something fundamental here, trapped in some this nightmare. Do I need to use bind or call to pass the this reference to requestAnimationFrame?

var THREE = THREE || {};
var SceneBuddy = SceneBuddy || {};

SceneBuddy = function(scene, camera) {
    this.scene = scene;
    this.camera = camera;
    this.sceneClock = new THREE.Clock();
    this.renderer = {};
    this.resolution = {};
    this.controls = {};
};
//Start Animate
SceneBuddy.prototype.startAnimate = function() {
    requestAnimationFrame(this.startAnimate); //this does not work, type error
    this.render.call(this);
};
//Render Function
SceneBuddy.prototype.render = function() {
    var delta = this.sceneClock.getDelta();
    this.controls.update(delta);
    this.renderer.render(this.scene,this.camera);
};

//Setup Renderer
SceneBuddy.prototype.initRenderer = function(resolution) {
    if (!Detector.webgl) {
        Detector.addGetWebGLMessage();
        return;
    }
    else {
        var renderer = new THREE.WebGLRenderer({
            antialias: true,
            preserveDrawingBuffer: true
        });
        renderer.setSize(resolution.x, resolution.y);
        renderer.shadowMapEnabled = true;
        this.resolution = resolution;
        this.renderer = renderer;
    }
};

I am using currently using SceneBuddy like this :

  var camera = new THREE.PerspectiveCamera(75, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 100000);
  var scene = new THREE.Scene();
  var sceneBuddy = new SceneBuddy(scene, camera);
  sceneBuddy.initRenderer({x: 940, y: 400});
  sceneBuddy.attachRenderer(container); //attaches renderer to dom element
  sceneBuddy.initControls();
  sceneBuddy.startAnimate(); // broken.
like image 762
mhilmi Avatar asked Mar 14 '13 23:03

mhilmi


1 Answers

Use bind when passing a function to specify what this will be when the function is called:

SceneBuddy.prototype.startAnimate = function() {
    requestAnimationFrame(this.startAnimate.bind(this));
    this.render();
};
like image 163
Dennis Avatar answered Oct 17 '22 23:10

Dennis