Menu

Event Listening

Winston Tamblyn

Event Listening

CraveJs is built to be event-driven, allowing objects to listen for and dispatch events. One of the first events you're going to what to work with is the ENTER_FRAME event of the stage. Listening for an event calls a function when a particular event is dispatched, passing the event to the function as it's only argument.

This simple example creates a box, adds it to the display list, listens for the ENTER_FRAME event of the stage, and moves the box 5 pixels to the right each frame.

package({
    Main : {
        extends : crv.display.Sprite,

        constructor : function() {
            var box = new crv.display.Sprite();
            box.width = 50;
            box.height = 50;
            box.background = "#cc0000";
            this.addChild(box);

            this.stage.addEventListener(crv.events.Event.ENTER_FRAME, function(e) {
                stage.x += 5;
            });
        }
    }
});

This example demonstrates how we can listen for CLICK events on instances of an [InteractiveObject]. It logs the stage to the console.

package({
    Main : {
        extends : crv.display.Sprite,

        constructor : function() {
            this.stage.addEventListener(crv.events.MouseEvent.CLICK, function(e) {
                console.log(this);
            });
        }
    }
});

Notice: The keyword this pertains to the object we have added an event listener to, in this case stage.


Related

Wiki: CraveJs