0

I'm quite new to JS's prototypying but not to oop in general. New to easeljs, however. Having said that, i've been trying to get an object variable triggered by a click event, and i REALLY can't seem to find a decent way of doing it.

Trying to build a clickable 2D "board", here is my test code:

(function() { //"Class"

        Brick = function() {
            this.initialize();
        };

        var p = Brick.prototype = new createjs.Container();
        p.Container_initialize = p.initialize;

        p.initialize = function() {
            this.Container_initialize();
        };

        p.create = function(row, column) {
            this.row = row;
            this.column = column;

            //Shape
            this.square = new createjs.Shape();
            this.square.graphics.beginFill("green").drawRect(0, 0, brickSize, brickSize);
            this.x = (brickSize * column) + (Game.padding * column); // Add some padding
            this.y = (brickSize * row) + (Game.padding * row); // Add some padding
            this.addChild(this.square);

            this.addEventListener("click", function(event) { console.log(this.row)})                
        };

    })();

After this I just create a few Bricks cycling through a multidimensional array cycle, and add them to the stage. The board shows perfectly, however, i keep getting "undefined" while cliking. console.log(event.currentTarget.row) works though, but not sure it's the way to go.

Thanks!

Joe Bone
  • 41
  • 3

1 Answers1

0

It's better not to create an instance of Parent to set the prototype of Child, use Object.create and shim it for older browsers:

var p = Brick.prototype = Object.create(createjs.Container.prototype);

Your event handler has the wrong value for this. The this value is the invoking object and is determined when invoking the function not when declaring it. You can fix that in the following way:

    p.create = function(row, column) {
        //.... not changed
        var me = this;
        this.addEventListener("click", function(event) { 
          console.log(me.row)})                
    };

If you use Chrome or Firefox with firebug it's sometimes better to just console.log(this) and click on the logged item for closer inspection.

More info about prototype can be found here.

Community
  • 1
  • 1
HMR
  • 37,593
  • 24
  • 91
  • 160