views:

941

answers:

2

I have written a utility library that contains some of my most used functions. There I have a wrapper for ResourceManager.getString to simplify using the resource manager in non-UI classes:

package
{
    import mx.resources.ResourceManager;
    /**
     * Convenience function to return a localized string
     * */
    [Bindable("change")]
    public function _s(bundle:String, resourceName:String):String
    {
        return (ResourceManager.getInstance().getString(bundle, resourceName));
    }
}

The problem is, that when the localeChain is changed, the function won't get called, while when invoking resourceManager.getString everything works as expected.

Since it is just a wrapper, I can easily switch back to the "long" notation, but I'm curious how I would achieve the desired behaviour.

A: 

You just need to bind to the ResourceManager's change event, and redispatch it to execute bindings for _s. Something like this:

import flash.events.Event;

import mx.binding.utils.BindingUtils;
import mx.resources.IResourceManager;
import mx.resources.ResourceManager;

/**
 * Convenience function to return a localized string
 * */
[Bindable("change")]
public function _s(bundle:String, resourceName:String):String
{
    return (resourceManager.getString(bundle, resourceName));
}

override protected function createChildren():void
{
    super.createChildren();
    BindingUtils.bindSetter(dispatchChange, resourceManager, "change");
}

private function dispatchChange(event:Event):void
{
    dispatchEvent(new Event("change"));
}

That's just a sample include script (include "resource_wrapper.as"), it shouldn't work out of the box, but you could modify it however.

The only problem with include is that you have to include it in lots of files manually. But that is the only way you can make it one "dot" deep:

  • include: Makes it like getString() (or _s());
  • normal: Makes it like resourceManager.getString()
  • singleton: Makes it like ResourceManager.getInstance().getString()

Hope that helps, Lance

viatropos
Thanks for the guidance.
flocki
A: 

Unfortunatley, the code Lance posted does not work. I have an updated version. However This cannot be used with a global public function, as I wanted it to work. It still has to be included in every file to be used. As such it is not really useful for a swc

// ActionScript file
import flash.events.Event;

/**
 * Convenience function to return a localized string

 * */
[Bindable("change")] 
public function _s(bundle:String, resourceName:String):String
{
    return (resourceManager.getString(bundle, resourceName));
}
override protected function createChildren():void
{
    super.createChildren();
    resourceManager.addEventListener(Event.CHANGE, function(e:Event):void {
            dispatchEvent(new Event(Event.CHANGE));     
        } 
    );
}
flocki