Gamua / Starling-Framework

The Cross Platform Game Engine
http://www.starling-framework.org
Other
2.87k stars 826 forks source link

ENTER_FRAME event dispatched twice per frame in a specific situation #826

Closed PrimaryFeather closed 8 years ago

PrimaryFeather commented 8 years ago

As reported by Eyal Katz in this forum thread:

I think I found a bug in DisplayObject.addEventListener when adding ENTER_FRAME events, and will want your attention about it.

In DisplayObject.addEventListener, Starling assumes that if an object is already on stage, then its ADDED_TO_STAGE event will not be called (but this can actually happen when the entire code is running during an Event.ADDED listener, which is prior to ADDED_TO_STAGE).

This code will reproduce the bug:

var test:Sprite = new Sprite();
test.addEventListener(Event.ADDED, onAddedToSprite);

// Adding test to a Sprite is ALREADY on stage
spriteOnStage.addChild(test);

function onAddedToSprite(e:Event):void {
    test.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

function onEnterFrame(e:Event):void {
    // We'll end up here TWICE on every frame...
    trace("I will be printed twice in every frame!" + Starling.current.frameID);
}