Integrate Flash with Flex

One problem I came across when using flex is that sometimes I want to be able to manipulate buttons or movieclips created in flash authoring within flex environment.

Some may suggest using LocalConnection class, but that might be the last solution you would want to consider, as scattering codes in both flex and flash is absolutely a pain for later maintainence.

Another way is to use flex component kit to convert native flash buttons into flex component so that you can use them the same way as other components in flex. However, there are situations this would bring up layout problems. So now you would think to yourself, there’s gotta be a way to use flash authoring buttons in flex applications.

Well, there is.

The current choice of mine is use SWFLoader class to load swf file created by flash authoring into flex at runtime. As soon as it’s loaded, you can use SWFLoaderclassInstance.content[”myButton”] to access “myButton” you created in flash.

This sure works, but if you dig in a bit deeper, you’ll find out that this alone will lead to lots of problems in terms of OOP principles. Here are a couple of problems:

1) you can’t access this button until the flash is fully loaded by SWFLoader class instance.

2) you have to make the SWFLoader object accessible to every class from which you want to refer to the swf elements(”myButton” in this case), plus, considering the first problem, just imagine what a mess it would be if you have to add all the listeners in these classes too for SWFLoader’s complete event.

3) this cluster of code “SWFLoaderclassInstance.content[’myButton’]” is just not clean enough

In order to solve all of these problem, here the Adapter design pattern comes to the rescue.

Adapter, as self-explanatory as it is, is a way to adapt old class API into a set of new interfaces so that it’s applicable in new situations.

Three elements are involved in a typical adapter pattern: adaptee(SWFLoader class), a public interface(IAdapter), adapter(Adapter)

For example:
(无actionscript标签,暂用java代替)
IAdapter.as
package
{
  public interface IAdapter
  {
    function getButton() : SimpleButton;
  }
}

Adapter.as
package
{
  public class Adapter implements IAdapter
  {
    private var _adaptee : SWFLoader;

    public function Adapter( swfLoader : SWFLoader ) : void
    {
      _adaptee = swfLoader;
    }

    public function getButton() : simpleButton
    {
      return _adaptee.content[”myButton”] as SimpleButton;
    }
  }
}


Of course, there is a good chance that you want to retrieve only one and the same one instance of the Adapter class. To combine it with singleton pattern, you’ll be able to achieve that.

Now you can safely use AdapterInstance.getButton to retrieve the button instance from flash authoring without throwing an error even if the swf file is not fully loaded yet.

 

你可能感兴趣的:(Flex,Flash,oop,Access,actionscript)