Flex / AS3 Проблема прослушивания события, отправленного из класса Singleton - PullRequest
0 голосов
/ 08 мая 2009

У меня есть одноэлементный класс для глобального доступа к информации конфигурации. Этот одноэлементный класс с именем ConfigurationData расширяет EventDispatcher. Вот класс (обратите внимание, что я упустил некоторые вещи, такие как объявления переменных, чтобы сократить это):

/**
* Dispatched when the config file has been loaded.
*/
[Event (name="configurationLoaded", type="flash.events.Event")]

/**
* Dispatched when the config file has been loaded.
*/
[Event (name="configurationLoadFailed", type="flash.events.Event")]

public class ConfigurationData extends EventDispatcher{
    // Event name constants.
    public static const CONFIGURATION_LOADED:String = "configurationLoaded";
    public static const CONFIGURATION_LOAD_FAILED:String = "configurationLoadFailed";

    // The singleton instance.
    private static var singleton:ConfigurationData;

    /**
    * Don't call the constructor directly, use getInstance() instead.
    */
    public function ConfigurationData(pvt:PrivateClass){
        // init
    }

    /**
     * Get the singleton ConfigurationData. 
     * @return The ConfigurationData instance.
     */
    public static function getInstance():ConfigurationData{
           if ( !ConfigurationData.singleton ) ConfigurationData.singleton = new ConfigurationData(new PrivateClass());
           return ConfigurationData.singleton;
       }

       public function initialize():void{
        var configureService:HTTPService = new HTTPService;
        configureService.url = _config_base_url + _config_path;
        configureService.addEventListener(FaultEvent.FAULT, onConfigureFault);
        configureService.addEventListener(ResultEvent.RESULT, onConfigureResult);
        configureService.send();
       }

       private function onConfigureResult(event:ResultEvent):void{
        var i:int = 0;
        for(i=0; i<event.result.carriers.carrier.length; i++){
            _mobile_carriers.addItem({label:event.result.carriers.carrier[i].name, data:event.result.carriers.carrier[i].id});
        }
        dispatchEvent(new Event(CONFIGURATION_LOADED));
    }

    private function onConfigureFault(event:FaultEvent):void{
        _mobile_carriers = _default_carriers as ArrayCollection;
        dispatchEvent(new Event(CONFIGURATION_LOAD_FAILED));
    }
}

// This class is used to ensure that the ConfigurationData constructor can't be called directly,
// getInstance() must be used instead. 
class PrivateClass {
    public function PrivateClass() {}
}

Затем у меня есть компонент MXML, который прослушивает событие CONFIGURATION_LOADED:

ConfigurationData.getInstance().addEventListener(Event.CONFIGURATION_LOADED, onConfigurationLoaded);

По какой-то причине это приводит к следующей ошибке: 1119: Доступ к возможно неопределенному свойству CONFIGURATION_LOADED через ссылку со статическим типом Class.

Кто-нибудь знает, как это исправить, чтобы я мог прослушать событие?

Спасибо!

1 Ответ

6 голосов
/ 08 мая 2009

Вы пытаетесь получить доступ к статическому константу в классе Event, который не существует: Event.CONFIGURATION_LOADED.

В этом случае вы захотите создать собственный класс Event:

public class ConfigurationEvent extends Event
{   
    public static const CONFIGURATION_LOADED:String = "configurationLoaded";
    public static const CONFIGURATION_LOAD_FAILED:String = "configurationLoadFailed";

    public function ConfigurationEvent(type:String)
    {
         super(type);
    }
}

Отправляйте и слушайте эти пользовательские события вместо Event.CONFIGURATION_LOADED:

dispatchEvent(new ConfigurationEvent(ConfigurationEvent.CONFIGURATION_LOAD_FAILED));

ConfigurationData.getInstance().addEventListener(ConfigurationEvent.CONFIGURATION_LOADED, onConfigurationLoaded);
...