0

I am creating a js class and implementing some Kinetic.js classes and methods. I am not sure what is the correct way to set one of my class variables. Here I have:

function Canvas(){
  this.stage;
  this.backgroundLayer;
}

Canvas.prototype.init = function(w, h){
  this.stage = new Kinetic.Stage({
    container: 'container',
    width: w,
    height: h
  });

  this.backgroundLayer = new Kinetic.Layer();
  this.stage.add(this.backgroundLayer);
}

Canvas.prototype.addImg = function(){
  var imageObj = new Image();
  imageObj.onload = function() {
    var yoda = new Kinetic.Image({
      x: 200,
      y: 50,
      image: imageObj,
      width: 106,
      height: 118,
      draggable: true
    });

    this.backgroundLayer.add(yoda);
  };
  imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
}

But, at this line:

this.backgroundLayer.add(yoda);

I get this console error:

Uncaught TypeError: Cannot call method 'add' of undefined 

Being new to JS, I am assuming that this.backgroundLayer is not in scope and therefore undefined. Is this correct, and if so, how would I rectify the problem? I tried setting var v = this.backgroundLayer and passing it into the function as a parameter, and then adding the layer like so: v.add(yoda), but that returned Uncaught TypeError: Object # has no method 'add'. Seemed in my mind like it was a possible solution, but like I say, I'm a bit new to javascript.

jordan
  • 6,382
  • 8
  • 38
  • 72

1 Answers1

1
Canvas.prototype.addImg = function(){
  var self = this
  var imageObj = new Image();
  imageObj.onload = function() {
    var yoda = new Kinetic.Image({
      x: 200,
      y: 50,
      image: imageObj,
      width: 106,
      height: 118,
      draggable: true
    });

    self.backgroundLayer.add(yoda);
  };
  imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
}

Keep a reference to this from the previous context. It's a confusing feature of JavaScript that this is changing depending on context.

TGH
  • 37,121
  • 10
  • 94
  • 126
  • That's quite confusing. I'll read into this more. Thanks for that tip! – jordan Feb 05 '14 at 04:30
  • For anybody looking to read further into this topic: http://stackoverflow.com/questions/962033/what-underlies-this-javascript-idiom-var-self-this – jordan Feb 05 '14 at 04:31