2

I keep having problems trying to reuse elements using the easeljs library. Whether I use the clone() method, where I can only get one instance and then events like onPress will stop working for the new elements.

Adding the same object on more than one container will make the object to disappear everywhere. I keep having to find workarounds around this, messing up my code and wasting resources.

Thanks in advance for any help or tip.

chrysillo
  • 732
  • 2
  • 9
  • 17

2 Answers2

6

if you are using Shape's Graphics, you might want to consider passing true as a parameter.

var boxClone = box.clone(true);

from CreateJs documentation: http://www.createjs.com/Docs/EaselJS/classes/Shape.html#method_clone

clone ( recursive )

Returns a clone of this Shape. Some properties that are specific to this instance's current context are reverted to their defaults (for example .parent).

Parameters: recursive

If true, this Shape's Graphics instance will also be cloned. If false, the Graphics instance will be shared with the new Shape.

Community
  • 1
  • 1
marcosbernal
  • 1,066
  • 8
  • 4
1

How about something like this? Not sure if this is what you are after but... Maybe it will help someone.

var canvas, stage;

    function init() {
        canvas = document.getElementById("testCanvas");

        //check to see if we are running in a browser with touch support
        stage = new createjs.Stage(canvas);
        createjs.Ticker.setFPS(24);
        createjs.Ticker.addListener(window);

        var width = 50;
        var height = 50;
        var padding = 5;
        var box = new createjs.Shape();
        box.graphics.beginFill("#FF0099").drawRect(0, 0, width, width).endFill();

        var l = 25;
        var cols = 7;
        for(var i=0;i<l;i++) {
            var boxClone = box.clone();
            boxClone.x = (width+padding) * (i%cols);
            boxClone.y = (height+padding) * (i/cols|0);
            boxClone.index = i;
            boxClone.onClick = handleClick;
            stage.addChild(boxClone);
        }
    }

    function handleClick(event) {
        console.log(event.target);
    }

    function tick() {
        stage.update();
    }