Search code examples
javascriptclassevent-handlingdom-eventseaseljs

Make extended shape class listen to stagemousedown event


I have created player class in EaselJS by extending shape like so:

var Player = createjs.extend(function Player (color, x, y) {
    this.Shape_constructor();
    this.x = x;
    this.y = y;
    this.graphics.beginFill(color).drawCircle(0, 0, 10);
}, createjs.Shape).constructor;
createjs.promote(Player, 'Shape');

I would like my player to listen to stagemousedown event, but I don't know how to access it, since it can only be applied to instance of Stage class.

Is there a way to propagate that event to all objects in the stage? I can't find any useful info in the documentation.


Solution

  • Any child of the stage can access the stage using the getStage() method. This will return null in the constructor (since the child is not on stage until addChild is used.

    I would recommend making a stage variable accessible to your children (global is the easy way), and then just listen there.

    // In the global scope
    var stage = new createjs.Stage("canvasId");
    // Or put it in the global scope
    window.myStage = stage;
    

    Then it is accessible for any children.

    stage.on("stagemousedown", handleStageClick);
    

    Remember to clean up these listeners when you are done, otherwise they will just stack up. The on method creates a method binding behind the scenes, so you will have to store it off to remove it later.

    this.listener = stage.on("stagemousedown", handleClick);
    // On clean-up
    this.off(this.listener);
    

    Hope that helps.