вызвать функцию в приложении из preloader как код - PullRequest
0 голосов
/ 29 февраля 2012

Я хочу вызвать функцию в главном приложении flex из пользовательского кода предварительной загрузки в ActionScript до того, как оно отправит событие complete.Также я хочу знать, как вызвать функцию в коде предварительной загрузки из приложения

Спасибо

1 Ответ

0 голосов
/ 29 февраля 2012

Таким образом, в методе инициализации preloader вы можете использовать следующую строку для получения приложения:

        parentApplication = event.currentTarget.loaderInfo.content.application;

наш предварительный загрузчик реализовал пользовательский интерфейс под названием IPreloader, а наше приложение реализовало пользовательский интерфейс под названием IPreloaderApp, IPreloaderопределяется как:

package com.roundarch.adapt.preloader
{
    import mx.preloaders.IPreloaderDisplay;

    public interface IPreloader extends IPreloaderDisplay
    {
        /**
         * Setting this will update the preloader's percentage bar or graphic.
         */
        function set percentage(value:Number):void;
        function get percentage():Number;

        /**
         * Sets the status (if available) on the preloader.
         */
        function set status(value:String):void;

        /**
         * This will communicate to the preloader that loading of all application
         * properties is complete.
         */
        function loadingComplete():void;

        /**
         * This will tell the preloader that there has been an error loading the application.
         *
         * The preloader will probably want to display this error message in a nice display to
         * the user.
         *
         * @param errorString The error message to display.
         * @param fatal If true, the preloader should act as if the application will not run perhaps
         * by notifying the user that they cannot continue.
         * @return Should return true if the error was properly handled.
         */
        function displayError(errorString:String, fatal:Boolean=false):Boolean;

        /**
         * Returns true if this IPreloader implementation can handle displaying loading
         * errors through the error(...) method. If false, the implementing application will
         * need to notify the user of any errors itself.
         */
        function get canDisplayErrors():Boolean;
    }
}

и для IPreloaderApp

package com.roundarch.adapt.preloader
{

    /**
     * Any application which uses an IPreloader as its preloader will be
     * required to implement this interface or throw an error.
     */
    public interface IPreloaderApp
    {
        /**
         * Once the application has loaded and initialized, this method will be called on the
         * application and the preloader will be passed in so the app can make updates to it.
         */
        function preloaderInit(preloader:IPreloader):void;
    }
}

Также стоит отметить, что если приложение добавляется за предзагрузчиком, а не впереди (поведение по умолчанию), товы не увидите оповещения, которые выдает приложение, поскольку они будут находиться за предварительным загрузчиком, поэтому вы захотите изменить порядок.Вот небольшой фрагмент кода, который мы использовали, чтобы обойти это:

    private var removedOnce : Boolean;

    //When the Preloader class instance (this things parent) is removed from it's parent
    //add this to the stage, allows us to dispatch the complete event at the corret time
    //allowing the SystemManager to add the application to the stage and adding this at
    //index 0 to allow pop-ups to show over it.
    private function parentRemoved(event : Event) : void
    {
        if (!removedOnce)
        {
            removedOnce = true;

            stage.addChildAt(this, 0);
            ToolTipManager.enabled = false;
        }
    }

после того, как parentApplication установлен в обработчике инициализации preloader, как показано в верхней части этого поста, мы добавляем обработчик, чтобы поймать удаление preloaderSystemManager и повторно добавьте его (видимого мерцания нет)

        //Lets the system manager know to add the application to the stage
        //this will also remove the preloader for this reason I'm listening for the removal
        //then adding the preloader to the stage again
        parent.addEventListener(Event.REMOVED, parentRemoved);
        dispatchEvent(new Event(Event.COMPLETE));

Еще одна вещь, на которую следует обратить внимание, это то, что вы не хотите «загрязнять» свой код предварительной загрузки какими-либо классами Flex, если вывключите вещи из фреймворка, вам в конечном итоге придется загрузить весь фреймворк в память до того, как начнется предварительный загрузчик (что может быть очень сложно).

...