ActionScript Design Pattern Samples: The Singleton

Posted in ActionScript, Design Patterns, Flex, How-To on March 10th, 2010 by Kalen Gibbons

I’ve decided to write a short blog series on ActionScript design patterns. This series will NOT contain in-depth discussions about the patterns, when to use them, why to use them, or any of that. Rather, each post will have a working example that demonstrates a pattern in use, and will be accompanied by a brief description of key points. These working samples may serve as a functional reference for myself or anyone else who may find them useful. Enjoy.

The Singleton Pattern

The Singleton Pattern is a very commonly used pattern in ActionScript; Cairngorm’s ModelLocator is one of the most popular examples that people may be familiar with. In short, a Singleton is used when you want to guarantee that only one instance of a class can exist.

Why would you want this? Well, to avoid conflicts for one. Imagine you have an application with a shopping cart, and various items can be added to the cart from different sections of your application. You’d typically want all a user’s products in a single shopping cart. If multiple carts existed each would have their its products, its own total, and it would be difficult (and problematic) to manage them all at checkout. So how could you ensure that only one shopping cart exists, especially if you have multiple developers working on the different sections of the application? The answer is to make the shopping cart class a Singleton, which ensures that only a single instance of the Singleton class can exist.

The Code

So, how can the Singleton pattern ensure that only one instance of a class exists? Simple, limit access to the class’ constructor and require the class to instantiate itself. This is typically done with a private constructor in other languages, but ECMAScript, the current standard that ActionScript 3.0 is based on, does not support private constructors. So instead, we create a class like the following:

  1. Prohibit constructor access: The easiest way to prevent access to a class’ constructor is to require a parameter that only the class itself has access to. In the example, the SingletonEnforcer class is declared in such a way that it cannot be accessed by any class other than ShoppingCart. Then, by requiring the SingletonEnforcer class to be passed into its constructor, the ShoppingCart class ensures that it cannot be instantiated by anything else; it’s responsible for it’s own creation.
  2. Provide a single entry point: Since Singleton classes cannot be instantiated directly, there needs to be an entry point for external classes to request an instance. The getInstance() method serves this purpose. It must be a static method for it to be exposed without requiring an existing instance of the class. This method simply checks to see if an internal instance exists (stored as the instance variable), creates an instance if not, and then returns that single instance.

The Sample

And here’s a working example, you can view the source code here.

Get Adobe Flash player

And that’s it. Please let me know if you have any questions, comments, or suggestions.


Learning Parsley, Part 1: Dependency Injection

Posted in ActionScript, Flex, How-To on November 9th, 2009 by Kalen Gibbons

SpiceFactorys Parsley FrameworkI decided to take a look at SpiceFactory’s Parsely framework for Flex, and I was pretty impressed. When I started to dig into the framework I discovered that although the framework’s documentation was very good, there weren’t many community examples or tutorials for the framework. So I decided to create a short series on getting started with Parsley. The examples in the series will be fairly simple and no advanced topics will be discussed; my aim is to help developers get a jump-start on development, by providing simple examples of working code.

Defining Object Dependencies

We’ll begin by learning how to add dependency injection into an application. First, we need to recognize our object dependencies. In the sample application below, the ContactList view requires the ContactManager model object to provide its data. In Parsley, marking that dependency as an injection point is as simple as adding the [Inject] metadata tag above the property declaration.

Parsley can also inject properties into constructors and other methods, and you can find more information on that here.

<mx:Script>

<![CDATA[

 

import com.kalengibbons.contactsManager.model.ContactManager;

 

[Inject]
[Bindable]
public var contactManager:ContactManager;

 

]]>

</mx:Script>

Creating the IOC Container

Next, we need to tell Parsley where to find the ContactManager class before it can inject it into the view. To do this, we need to add it to the IOC Container, which is responsible for wiring all our dependencies together. The container can be written as MXML, ActionScript, XML, or a combination of the three. For more information on using these methods you can view the documentation here. For this example, we will look at an MXML configuration. To do this, simply create an MXML file with mx:Object as the root tag, and add references to the objects that we will need to wire, like so:

<?xml version="1.0" encoding="utf-8"?>
<mx:Object xmlns="*" xmlns:mx="http://www.adobe.com/2006/mxml"

xmlns:model="com.kalengibbons.contactsManager.model.*">

 

<model:ContactManager />

 

</mx:Object>

Wiring the View

The framework won’t know to look in our ContactList view for injection points unless we tell it to. To do this, we need to also add the view into the IOC Container. There are two ways of doing this. We could explicitly declare it in the container like we did in the previous step for the ContactManager. But for views, Parsley allows us to dynamically wire them by simply dispatching a single configuration event like so:

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
addedToStage="this.dispatchEvent( new Event(‘configureView’, true) );">

The configureView event tells Parsley that the view should be added to the IOC Container at runtime.

Initializing the Framework

Finally, to put it all together, we need to initialize the framework and provide Parsley with the IOC Container we created. We want to do this as early as possible so doing this on the addedToStage event is common practice. Simply call the FlexContextBuilder.build() method and provide the IOC Container and the root DisplayObject used for wiring (typically the application root).

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"

xmlns:views="com.kalengibbons.contactsManager.views.*"
addedToStage="addedToStageHandler()">

 

<mx:Script>

<![CDATA[

 

import com.kalengibbons.contactsManager.config.ContactManagerConfig;
import org.spicefactory.parsley.flex.FlexContextBuilder;

 

private function addedToStageHandler():void{

// configure the IoC container
FlexContextBuilder.build(ContactManagerConfig, this);

}

]]>

</mx:Script>

 

<views:ContactList width="100%" height="100%" />

 

</mx:Application>

Here is a working example of the code. The application is very simple; when you click the button it simply populates the ContactModel object with data, which is bound to the DataGrid. The key is to notice how the ContactModel has successfully been injected into the view.

You can view the source code here.

Get Adobe Flash player

Points to Remember

  • Dependency injection takes time, and your objects might not be immediately available. In your views, even after the creationComplete event, your objects may still be null. So what you need to do is use [Init] metadata to designate a function for Parsley to run after injection is complete. Using this instead of a Flex event will ensure that your objects are all available and ready for use.
  • Don’t forget to add the application root to the IOC Container, if necessary. Even though you may initialize the framework in the application root, and use it as the view root of the Context, you will still need to dispatch the configureView event if you need dependency injection to take place in the application root.

Conclusion

If you haven’t done so already, please read the Parsley Documentation for more information about dependency injection and the Parsley framework. And like I stated in the intro, I’m new to Parsley myself so if anyone would like make corrections or suggest any best practices, please feel free to do so in the comments.


Tags: , ,

Update: Debugging Flex on a remote server

Posted in Flex, How-To, Tips & Tricks on October 12th, 2009 by Kalen Gibbons

In a previous post I described a hack I used for debugging Flex applications on a remote server. Well, shorty after making that post I stumbled upon a much better way of doing this. Flex Builder actually has functionality built into it to allow remote debugging, you just need to know where to find it.

  1. First, compile a debug version of your application and upload it to your remote server.

  2. Second, go to the Run/Debug Settings panel by clicking Project >> Properties and selecting the Run/Debug Settings option from the list. There, you should see another list of launch configurations for your project. Most likely, you’ll only have one, which will match the name of your application. Select it and click on the “Edit…” button.

  3. Next, find the “URL or path to launch” section and deselect the “Use defaults” checkbox. Within the first text input titled “Debug,” place the URL to your remote server. This URL can point to the SWF file or to an HTML page that loads the SWF, the debugger will connect either way.
    If you’re connecting to the SWF directly you may need to add ?debug=true to your querystring. If you are connecting to an HTML page – make sure it loads the debug version of your SWF and not the release build.

  4. Finally, save your project properties and run the debugger as normal. You’ll see that the debugger will connect to the SWF file on your remote server and you can debug the same way you would locally, using breakpoints, expressions and everything else.

  5. That’s it… enjoy!


Tags: ,

Debugging Flex on a remote server

Posted in Flex, How-To, Tips & Tricks on July 2nd, 2009 by Kalen Gibbons

Note: An update to this topic has been posted here. It provides a better solution than the one offered below, so I recommend you check it out before continuing.

Have you ever had a Flex application that worked fine in your development environment but not when you moved it to your production server? How do you debug the problem?

You can use the following trick to enable Flex Builder to establish a debug connection to a remote server.

  1. First, compile a debug version of the application and deploy it to your remote server.
  2. Then go into the project’s properties in Flex Builder (Project >> Properties >> Flex Build Path) and change the “Output folder URL” to an invalid URL (this can be almost anything).

    Remote Debug: Bad URL
  3. Compile your application again in debug mode. This time, Flex Builder will launch the invalid url and will not be able to connect to the debugger.

    Remote Debug: Connecting to debugger
  4. While Flex Builder is waiting to connect to the debugger, navigate to the debug SWF that you put on your remote server. Don’t forget to include ?debug=true in the querystring.
  5. Flex Builder will connect to the remote swf the same way it would have connected to your local version. You can use breakpoints, inspect variables, and do everything you could do locally.

    Remote Debug: Debug Panel

This trick comes in really handy when you have problem related to a specific environment. I hope this can help ease the pains of debugging for some of you.


Tags: ,

Creating a scroll-to list in Flex

Posted in ActionScript, Flex, How-To on June 1st, 2009 by Kalen Gibbons

Here is an example of how you can create a scroll-to list using the AnimateProperty class. In this example I’m using a repeater instead of a List for simplicity, but for large data sets this would not be recommended.

I have a DataGrid on the left hand side that simply lists the release date and title of several upcoming movie releases. If you click on a row, the list on the right will scroll to the details for the movie selected.

– View application source –

Get Adobe Flash player

The code is pretty straightforward, but there two main pieces to look at. The first is how to use the AnimateProperty class to scroll the list to the desired location. The second, is how to allow the last item in the list to scroll all the way to the top.

Scrolling to an item in the list

import mx.effects.easing.Sine;
import mx.effects.AnimateProperty;
import mx.events.ListEvent;
 
private var scrollAnimation:AnimateProperty = new AnimateProperty();
 
private function scrollToMovie(event:ListEvent):y{

var yPosition:int = movieWrapper.getChildAt(event.rowIndex).y;
scrollAnimation.stop();
scrollAnimation.property = "verticalScrollPosition";
scrollAnimation.easingFunction = Sine.easeOut;
scrollAnimation.duration = 900;
scrollAnimation.toValue = yPosition;
scrollAnimation.play([movieWrapper]);

}

Allowing the last list item to scroll to the top

private function addSpaceToBottom():void{

if(movieWrapper.numChildren > 2){

var lastChild:HBox = movieWrapper.getChildAt(movieWrapper.numChildren-2) as HBox;
var spacerHeight:int = movieWrapper.height – lastChild.height;
if(spacerHeight > 0)

spacerBottom.height = spacerHeight;

}

}

 


Tags: , ,