Search code examples
javascripthtmlwebkiteaseljscreatejs

Sending events to createjs.Stage children (or JavaScript objects in general)?


I am developing an HTML5 application with EaselJS that uses a canvas element covering the entire window to display its interface. I'm using the following function to fix canvas bounds in case user resizes the window:

function resizeCanvas(event) {
  if (window.onresize == null) window.onresize = resizeCanvas;
  canvas.width  = document.body.clientWidth;
  canvas.height = document.body.clientHeight;
  stage.update();
}

However, when canvas bounds change, so must some of its elements (children of the createjs.Stage() object). Ideally, I'd like resizeCanvas() to simply dispatch an event and have the appropriate stage.children() objects respond. I tried adding the following the line in the above function: stage.dispatchEvent(event) and creating the shape objects like this:

var grid = new createjs.Shape(drawGrid());
grid.addEventListener('resize', function(evt) { alert(evt); }, false);
stage.addChild(grid);

This, however does not work and it seems I grossly misunderstand Events.


Solution

  • The addEventListener() will listen for events dispatched by the object itself, not received by an object, so your line:

    grid.addEventListener('resize', function(evt) { alert(evt); }, false);
    

    will alert whenever the grid dispatches a resize-event, not when it receives one, so you would have to use grid.dispatchEvent('resize') in order to get the alert, in which case.. you already have the object, why dispatch the evnt, if you can call the size-method right away - it's like a chicken-egg issue in this case, it would make sense though if the grid had children listening to the event.

    If you really want to work with events here, you'd have to add a listener to a central object(probably the stage) for each element that you want to resize, like this:

    stage.addEventListener('resize', function(evt) { grid.resize(); });
    // the grid-object ofc needs a resize-method that handles the event
    // also: anonymous functions make this way a complete hassle, but
    // you will very likely need the scope of the 'grid' here...
    

    and finally you will need to have the stage dispatch the resize-event, so right befor you do that stage.update() in your resizeCanvas() you add:

    stage.dispatchEvent('resize');
    // optionally you can dispatch with an object that contains additional data
    

    What I would do (and I couldn't tell if this way is better or worse, it's just how I would do it): I would write a recursive method to call a resize-method on every child and their children, started by the stage instead of using events.