Search code examples
javascripthtmlfunctionkineticjs

Correct way to get/set Javascript members? (This issue using Kineticjs)


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.


Solution

  • 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.