Flex Part 03: The ModelLocator

The ModelLocator is an Action Script Class that is stored in the model directory.

This is a concept used in every Cairngorm application (see here for example) but you don't need the Cairngorm library in your project to use it. In fact, you don't need to know anything about Cairngorm to get started.

About the name

The ModelLocator holds instances of Model Objects, making them easy to locate and accessible from anywhere in the application.

Benefits of using the ModelLocator

The ModelLocator will make Flex development easier and more enjoyable. Here's how: All application data will be stored in one single place, accessible from anywhere in the application at any time. That one place is, of course, the ModelLocator.

Storing all application data in one place is a wonderful thing. Here's why: All user interface components can be bound to the data in the ModelLocator. This means that one change to data in the ModelLocator will update every single ui component that is bound to that data - anywhere in the application. You will be writing MXML and ActionScript for your views that looks like this:

Actionscript:
  1. <mx:Script>
  2.     <![CDATA[
  3.         import com.domain.project.model.ModelLocator;
  4.        
  5.         /**
  6.          * Get a reference to the one and only instance of the ModelLocator
  7.          */
  8.         [Bindable]
  9.         private var model:ModelLocator = ModelLocator.getInstance();
  10.     ]]>
  11. </mx:Script>
  12.  
  13. <!-- Bind ui components to the ModelLocator -->
  14.  
  15. <mx:Panel title="{model.selectedSchool.name}">
  16.     <mx:DataGrid dataProvider="{model.selectedSchool.students}"/>
  17. </mx:Panel>

Whenever the selectedSchool property of the ModelLocator is changed/updated, every control in the application that binds to that property will be updated as well.

Creating the ModelLocator

The ModelLocator is an Action Script Class generally named ModelLocator.as and is stored in the model directory.

In the code block above, the ActionScript comment reads "Get a reference to the one and only instance of the ModelLocator." If there were multiple instances of the ModelLocator, then multiple versions of our application data would exist. So there may be only one single instance of the ModelLocator class. An ActionScript Class that may be instantiated only once is called a Singleton, i.e. ModelLocator is a Singleton Class. (Code for a singleton class may be written many ways. The method that follows is the simplest example that I feel is appropriate. It is also perfectly acceptable for use in production applications, though arguably better solutions exist which I may write about at a later time.)

Let's start with the full code for ModelLocator.as:

Actionscript:
  1. package com.domain.project.model
  2. {
  3.     [Bindable]
  4.     public class ModelLocator
  5.     {
  6.         /**
  7.          * One and only instance of ModelLocator
  8.          */
  9.         private static var instance:ModelLocator = new ModelLocator();
  10.  
  11.  
  12.         /**
  13.          * Bindable application data
  14.          */
  15.         public var selectedSchool:School; // School Model Object
  16.  
  17.        
  18.         /**
  19.          * Constructor
  20.          */
  21.         public function ModelLocator()
  22.         {
  23.             if (instance) { throw new Error('Cannot create a new instance.  Must use ModelLocator.getInstance().') }
  24.         }
  25.  
  26.  
  27.         /**
  28.          * Return the one and only instance of ModelLocator
  29.          */
  30.         public static function getInstance():ModelLocator
  31.         {
  32.             return instance;
  33.         }
  34.     }
  35. }

Explaining the ModelLocator Code

As seen in the first code block, data in the ModelLocator is accessible from all parts of the application with the following code:

Actionscript:
  1. /**
  2. * Get a reference to the one and only instance of the ModelLocator
  3. */
  4. [Bindable]
  5. private var model:ModelLocator = ModelLocator.getInstance();

Notice that a new instance of the ModelLocator class is never created. Instead, a public static method method of the ModelLocator class named getInstance is called. The return value of that method is assigned to a variable in the view of the type ModelLocator. Examine the getInstance method:

Actionscript:
  1. /**
  2. * Return the one and only instance of the ModelLocator
  3. */
  4. public static function getInstance():ModelLocator
  5. {
  6.     return instance;
  7. }

The getInstance method returns a variable called instance. This variable is declared earlier in the class and holds the one and only instance of ModelLocator - aptly named instance. Find the instance variable in the ModelLocator.as code above. It looks like this:

Actionscript:
  1. /**
  2. * One and only instance of ModelLocator
  3. */
  4. private static var instance:ModelLocator = new ModelLocator();

Since an instance of ModelLocator resides in the variable instance and ModelLocator is a Singleton, no further instances may be created. If an attempt is made, the constructor will throw an error with the message, "Cannot create a new instance. Must use ModelLocator.getInstance()."

Storing Bindable Data

All application data will be stored as public variables which are bindable to components the application. An example of this is found in the ModelLocator.as code above and looks like:

Actionscript:
  1. /**
  2. * Bindable application data
  3. */
  4. public var selectedSchool:School; // School Model Object

Try it out - right click to view source

This simple application uses the concepts found in this and the previous two posts. It demonstrates setting data in the ModelLocator and binding to that data. In a later post I will present a much more elegant way of working with data in the ModelLocator.

Next ...

The next post in this series will be titled "Flex Part 04: Introducing Frameworks." This post will cover Cairngorm and other MVC frameworks conceptually - further posts will put those concepts into action.

Thank you for reading. Your comments are very much appreciated. Remember that these posts are living documents and will be updated over time as input is received and new ideas emerge. So, please, consider your comment a contribution.

9 Responses to “Flex Part 03: The ModelLocator”


  1. 1 Ben Throop

    Scot... really nice series. I haven't seen things taken from the ground up anywhere else and it's really useful. I'll be following along with each additional post.

    I've architected my app in a similar way but I combined the VO and the Model into a single class. I'm using XML for server communication and so I have a setXML and getXML (akin to your toVO and fromVO methods), but without a separate VO class. Are there any potential hitches that stand out to you in combining the model and VO?

  2. 2 T. Scot Clausing

    I have made an assumption in this series that I alluded to in Part 02 but never made clear. The assumption is that readers will be sending and receiving data using AMF (ActionScript Messaging Format) and mapping objects on the server to objects (VO's) in the Flex application. Using AMF for data transfer provides a much faster response time and allows strongly typed data to move between the server and the application.

    If you're not going that route then VO's may not be necessary (since the VO's primary purpose is to provide an object in the Flex app that maps to an object on the server).

  3. 3 Ben Throop

    Ah cool. What are you using on the back end? I'm using AMFPHP.

  4. 4 T. Scot Clausing

    Currently at work we are using Ruby on Rails with RubyAMF. <- A beautiful combo. At home I am using WebORB for PHP. I tried AMFPHP with great success and I favor its simplicity, but WebORB (at the time I made the decision) was better documented and had a more feature packed tool for testing. Should I reconsider?

    I would really like to see a demonstration of using ORM in PHP with AMF. That would be great. Anyone have an example of this?

  5. 5 T. Scot Clausing

    In response to using ORM (Object Relational Mapping) with PHP and AMF it sounds like there may be a couple options. Both solutions use Doctrine PHP for ORM. I will be looking into this further. If anyone else has additional resources or input, please let me know! Thanks.

    WebORB PHP
    http://www.themidnightcoders.com/forum/default.aspx?g=posts&t=356
    - Anyone have any more info on WebORB PHP and Doctrine?

    AMFPHP
    -Has an adapter for Doctrine built in (amfphp/core/shared/adapters/doctrineAdapter.php). I am very interested in this and hopefully will have a post about it soon.

  6. 6 Johan

    Scot - enjoying the series. Looking forward to future installments. Nice to be able to tap into some of the good things from frameworks like Cairngorm (ModelLocator) without having to get into Cairngorm.

  7. 7 Tanuvan

    Brilliant Series!!!

  8. 8 brad

    Pure genius! Thanks for the concise and well thought out tutorial on organizing data and code with Flex.

  9. 9 Todd

    Awesome series for a newbie to Flex like myself. I am building my first app and will apply these principals. Thanks for recommending how data should be stored within Flex.

Leave a Reply