0

I am doing some excercise, and I have issue with losing "this" context in a pipe method:

function Main() {
// something
this.render = function () {
    this.groups.forEach(function(g){
        renderGroup(g);
    });
    return this;
};
// something
this.pipe = function () {  
    this.render();                      // 1
    requestAnimationFrame(this.pipe);   // 2
    return this;
};
// something
}

Ad.1: that cause "this is undefined, so it has no render function"

Ad.2: if above commented, still "this" context is undefined so pipe is not a function

initialization:

function init () {
  var m = new Main();
  requestAnimationFrame(m.pipe);
}

window.onload = function () {
  init();
}

full object code:

function Main() {
this.canvas = document.createElement("canvas");
this.canvas.width = 1366;
this.canvas.height = 768;

this.canvas.style.width = this.canvas.width + "px";
this.canvas.style.height = this.canvas.height + "px";

this.groups = [];
window.app = {};

this.grain = 30 * 1000 * 60;
this.grainWidth = 30;

this.getGroups = function () {return this.groups;}
this.render = function () {
    this.groups.forEach(function(g){
        renderGroup(g);
    });
    return this;
};

this.ctx = this.canvas.getContext("2d");
this.pipe = function () {  
    this.render();        
    requestAnimationFrame(this.pipe);
    return this;
};

document.body.appendChild(this.canvas);

registerEvents();

}

the renderGroup is plain forEach.

What causes the context lost?

spazm
  • 4,399
  • 31
  • 30
Daniel Mizerski
  • 1,123
  • 1
  • 8
  • 24

2 Answers2

1

Simply bind the context you want pipe to be called with

this.pipe = function () {  
    this.render();                      // 1
    requestAnimationFrame(this.pipe);   // 2
    return this;
}.bind(this)
Mauricio Poppe
  • 4,817
  • 1
  • 22
  • 30
1

Maybe something like this?

requestAnimationFrame(this.pipe.bind(this));

JavaScript functions get this defined when they're called. You use pipe as callback, so the context for it becomes window since it's called from window.requestAnimationFrame.

Audrius Lubys
  • 626
  • 6
  • 7