CC-Archived / promise-as3

Promises/A+ compliant implementation in ActionScript 3.0
167 stars 52 forks source link

Promise-as3 lib help with stage observation #40

Closed Kalinovych closed 10 years ago

Kalinovych commented 10 years ago

Hello guys, I'm trying to learn how to use this lib and I need a bit of help. I have stuck at start with the simple task: Calling some function(init for example) i need to call a sequence of methods only if object is on stage or when it will be added to stage.

What is the best way to resolve it?

P.S. I have already implemented DeferredEventHandler(+DeferredEventHandlerAdapter) that can handle an events that resolve or reject it promise. It's cool when the event did not happened yet. But if required value is already available I need some advanced helpers...

In case of example above I'm plan to create some kind of DefferedStage or StagePromise that accept observable object as argument, and if object is on stage it resolves the promise otherwise it subscribes for the addedToStage event, so on...

Kalinovych commented 10 years ago

For now I have done with StagePromise with one static method "when". It may be not a correct solution in the context of promises because I'm newbie with the promises :)

public class StagePromise {
    public static function when( object:DisplayObject ):Promise {
        if ( !object ) {
            throw new ArgumentError( "Parameter object can't be null" );
        }

        const deferred:Deferred = new Deferred();
        if ( object.stage ) {
            deferred.resolve( object.stage );
        } else {
            object.addEventListener( Event.ADDED_TO_STAGE,
                    function ( event:Event ):void {
                        object.removeEventListener( Event.ADDED_TO_STAGE, arguments.callee );
                        deferred.resolve( object.stage );
                    } );
        }
        return deferred.promise;
    }
}
karfau commented 10 years ago

I don't see any problem with your code. Do you still have a question?

Kalinovych commented 10 years ago

Yes, I have one: how to reject a promise and break all next then() without throwing an Error?