aodz

FrameworkQuest 2008 Part 2: Get Control with Cairngorm

Posted on: January 16, 2009


FrameworkQuest Part 2 by Tony Hillerson
Find the original post here

FrameworkQuest 2008: Introduction
FrameworkQuest 2008 Part 2: Get Control with Cairngorm
FrameworkQuest 2008 Part 3: Agnostic Views with PureMVC
FrameworkQuest 2008 Part 4: IoC With Swiz
FrameworkQuest 2008 Part 5: Mate, the Pure MXML Framework
FrameworkQuest 2008 Part 6: The Exciting Conclusion

Carebear? Carhorn? What?

Cairngorm is the Flex Framework with the odd name that’s been around almost since the beginning of Flex. It was created by a company called iteration::two, which went on to become Adobe Consulting’s European practice around the same time Adobe acquired Macromedia. These guys had been using Flex very early on, and were some of the first to talk about how important it was to building business applications. They even wrote the first commercially available Flex book, which helped to lend Cairngorm a lot of credibility when they released it soon after.

So what’s a Cairngorm? The Cairngorms are a mountain range in Scotland and Cairn Gorm is one of the famous peaks in that range. It’s 4000 feet above sea level, which isn’t impressive on paper to a Colorado-an like me (we have 25 peaks over 14,000 feet, and 56 over 4000m, so nyah-nyah), but then again, we have a continent underneath us to prop things up a bit. I’d love to see the Cairngorms one day and I’m sure the highland beauty, if not the mass quantities of Scotch Whisky, would make a suitable impression.

So how do you pronounce it? Most people say “CAREn-gorm”, and some say “CARn-gorm” (for American English values of “care” and “car”). I have no idea, but I think the “car” version may be closer to the Scotch pronunciation.

If you’d like to learn more about Cairngorm, the documentation is here.

Now, back to Flex land, let’s see where we left off.

Reviewing our Mess

In the last episode of our series on Frameworks we looked at an AIR application created using Flex, but used no Flex framework. Here are a list of problems we hope to solve with a framework.

  1. 1. Poor Organization
  2. 2. Unstructured Application State
  3. 3. Bloated Views

MVC to the Rescue

Many of you have heard of the concept of the Model/View/Controller architectural pattern. When we apply this pattern to an application, the code is separated into three general concerns – the Model, the View, and the Controller.

The Model is responsible for holding the state of the application, which means any information that the application could display, any information that the application needs to use to contact services, and any information about a particular session with a user, like where they are in the application.

The View is responsible for displaying the data in the model and informing the rest of the application about user interaction, such as the click of a button.

There are a few rules that MVC applies to the model and the view. One is that the model should not know about the view. That means that however the data gets from the model to the view, the model can’t be the one putting it there. Conversely, the view shouldn’t act directly on the model to change its state. Another rule is that the view shouldn’t know about the controller. It doesn’t have a reference to any part of the controller, so it can’t change anything about the controller directly.

That leaves The Controller to somehow respond to user interaction notifications from the view and inform the model appropriately, possibly changing the state of the model. Then through some mechanism that makes sense, the view is updated to reflect the new state of the model.

MVC was created to help keep business logic and view logic separate so that, theoretically, changes in the one don’t require changes in the other. The principles of MVC are going to show up in all the frameworks we discuss, so keep them in mind.

Now let’s look at how Cairngorm does things.

Cairngorm: Dramatis Personae

Cairngorm is described by Adobe Consulting as a microframework, or a set of patterns available to developers to assist in building an application. Here’s a normal flow of operations and the Cairngorm classes that are exercised.

When the user takes some sort of action on the view, such as clicking a button, the view dispatches a CairngormEvent. This event informs the FrontController, which instantiates a Command. The command executes the business logic, and the event is responsible for passing data to the command about the user interaction.

The command can either take some action on the Model, or instantiate and act on a Business Delegate. The Business Delegate, or delegate for short, wraps the code required for a service call, so it acts like the service API to the rest of the application. This is important because when the service changes, the changes to the application can be minimized and ideally only the delegate needs to change. The delegate calls the service and then depending on the kind of service involved makes sure that the command is informed when the service call has returned. Then the command changes the state of the model, if necessary, and the model, through Flex’s binding, updates the view.

That was a whirlwind tour, but if we look at some code I think it will become a little clearer.

TwitteRIA on Cairngorm

First we’ll look at changes to the top-level application. The Script-block has changed to this:

twitteria_cairngorm/src/twitteria_cairngorm.mxml #6-13

<mx:Script>
<![CDATA[
     import com.insideria.twitteria.model.TwitteRIAModel;

     [Bindable]
     private var model:TwitteRIAModel = TwitteRIAModel.getInstance();
]]>

</mx:Script>

Now, all we do is get an instance to the model. The model instance is bindable so that the view can bind to properties on the model. I say the model because Cairngorm only has one. The code in the model goes as far as possible in ActionScript 3 to make sure that nothing can instantiate the model except the model’s class. If you haven’t seen a Singleton implementation in AS3, here our Model as an example. First, there’s a private class variable to hold the singleton instance:

twitteria_cairngorm/src/com/insideria/twitteria/model/TwitteRIAModel.as #10

private static var instance:TwitteRIAModel;

Then, since we can’t have private constructors in AS3, the constructor doesn’t allow any other class to call new TwitteRIAModel() unless it passes an instance of the Private class:

twitteria_cairngorm/src/com/insideria/twitteria/model/TwitteRIAModel.as #27-31 (formatted)

public function TwitteRIAModel(access:Private) {
      if (access == null) {
            throw new 
                 CairngormError(
                       CairngormMessageCodes.SINGLETON_EXCEPTION,
                       "XCLModelLocator"
                 );
       }
}

which is defined on line 45, outside the package, making it virtually invisible outside of this file.

twitteria_cairngorm/src/com/insideria/twitteria/model/TwitteRIAModel.as #45

class Private {}

And finally the getInstance method returns the instance, creating it if it hasn’t already been created.

twitteria_cairngorm/src/com/insideria/twitteria/model/TwitteRIAModel.as #33-38

public static function getInstance():TwitteRIAModel {
      if (instance == null) {
            instance = new TwitteRIAModel(new Private());
       }
      return instance;
}

So much for Singletons. We’ll have more to say about them later. Back to the Application. Now that we have the model to hold state for the application, we can point the ViewStack at the model.

twitteria_cairngorm/src/twitteria_cairngorm.mxml #23-26 (formatted)

<mx:ViewStack selectedIndex="{model.mainViewIndex}">
     <view:LoginView id="loginView" />

     <view:MainView id="mainView" />
</mx:ViewStack>

Also note that the LoginView and MainView here no longer share the username and password between them, nor does the LoginView inform the Application of the login event. We’ll get to how those changed in a moment. For now, there’s one last important line on the Application:

twitteria_cairngorm/src/twitteria_cairngorm.mxml #15

<controller:TwitteRIAController id="controller" />

The Cairngorm FrontController needs to be instantiated early in the application’s lifecycle, and that’s generally done by defining it in MXML right in the root application. Another thing that’s usually instantiated alongside the controller is the ServiceLocator, which is generally a file that defines any services the application accesses to keep them all in the same place. Since our application doesn’t use the normal HTTPService or RemoteObject you usually see in a Cairngorm application, we don’t use the ServiceLocator.

The Controller, as mentioned above, is what takes care of capturing dispatched CairngormEvents and instantiating and executing the corresponding commands. You never actually interact directly with the controller in code, but you do wire up events to commands there, as shown here:

twitteria_cairngorm/src/com/insideria/twitteria/controller/TwitteRIAController.as #13-17 (formatted)

private function initialize():void {
      addCommand(
           LogInEvent.LogIn_Event, LogInCommand);
      addCommand(
           LoadTimelineEvent.LoadTimeline_Event, LoadTimelineCommand);
      addCommand(
           SetStatusEvent.SetStatus_Event, SetStatusCommand);
}

Now whenever, for instance, a LogInEvent is dispatched, the FrontController instantiates a LogInCommand and executes it.

Logging In

Now lets look at logging in. Where before we just had the LoginView’s username and password bound to the MainView, we’re going to take a more scalable approach this time. What we really want is to keep the username and password around so that we can access them from anywhere we need them. That’s what the model is for. Now look at the LoginView’s login method, which before emitted an event:

twitteria_cairngorm/src/com/insideria/twitteria/view/LoginView.mxml #7-9

public function login():void {
      new LogInEvent(usernameText.text, passwordText.text).dispatch();
}

Now the method dispatches a LogInEvent, which holds a username and a password. When it’s dispatched with its own dispatch method, the LogInCommand is instantiated and executed, with the event passed along.

twitteria_cairngorm/src/com/insideria/twitteria/command/LoginCommand.as #13-19

public function execute(event:CairngormEvent):void {
      var evt:LogInEvent = event as LogInEvent;
      model.username = evt.username;
      model.password = evt.password;
      model.mainViewIndex = TwitteRIAModel.MAIN_VIEW;
}

After setting the username and password properties on the model to the values on the event, the command changes the mainViewIndex property to the MAIN_VIEW constant on the model. If you remember, the ViewStack in the application had its index bound to model.mainViewIndex.

twitteria_cairngorm/src/twitteria_cairngorm.mxml #23 (formatted)

<mx:ViewStack selectedIndex="{model.mainViewIndex}">

The constants on the model help give some idea what they are used for:

twitteria_cairngorm/src/com/insideria/twitteria/model/TwitteRIAModel.as #16-19

public static const LOGIN_VIEW:int  = 0;
public static const MAIN_VIEW:int   = 1;
[Bindable]

public var mainViewIndex:int        = LOGIN_VIEW;

So when the LoginCommand changes the mainViewIndex to MAIN_VIEW, the ViewStack changes to show MainView.

There are two examples of how the Cairngorm model holds both application state and view state. You also see can see an example of how a Cairngorm command is tasked with a specific responsibility, in this case setting credentials and making sure the view state matches the logged in view – basically taking care of what needs to be done to log in, just like the command name leads you to believe. In this way the commands and FrontController together make up the Controller part of MVC for Cairngorm.

I like that about Cairngorm. If you want to know how the app works and where that work is done, you just need to look through the command directory and see a list of descriptive verbs that tell you what takes place and what class does it.

Loading the Timeline

Now let’s look at how we load the timeline. Again, when the MainView’s creation is complete, the init method is called:

twitteria_cairngorm/src/com/insideria/twitteria/view/MainView.mxml #14-16

private function init():void {
      new LoadTimelineEvent().dispatch();
}

Instead of doing any work inside the MainView, like we did before, now we dispatch a CairngormEvent that loads the timeline. That event corresponds to the LoadTimelineCommand.

twitteria_cairngorm/src/com/insideria/twitteria/command/LoadTimelineCommand.as #16-20

public function execute(event:CairngormEvent):void {
      var evt:LoadTimelineEvent = event as LoadTimelineEvent;
      var delegate:TwitterDelegate = new TwitterDelegate(this);
      delegate.loadTimeline();
}

The execute method doesn’t do that much, in fact it delegates responsibility to the TwitterDelegate. If you remember, delegates are the guys that wrap the service API and cushion the rest of the app from changes to the services. All we need to know here is that the delegate will load the timeline, and we ask it to do so.

I should make a note here that I’m breaking a bit with Cairngorm convention. Generally Cairngorm has you define one delegate for each event/command pair. That gets a little chunky for my taste, and instead I usually define one delegate for every resource I’m accessing on the service side. For instance if I had a user service with an API for creating, updating, deleting, getting a user, and getting all users, I’d have one delegate for users which would have methods to execute each of those operations. Again, this is not Cairngorm convention, this is my way of doing things. It’s not like I’m hurting Cairngorm, though, and it shows that the framework is flexible enough to meet your needs, or in this case, a matter of taste.

Let’s look at the delegate. In the constructor you can see more characteristic Cairngorm code:

twitteria_cairngorm/src/com/insideria/twitteria/business/TwitterDelegate.as #20-21

public function TwitterDelegate(responder:IResponder) {
      this.responder = responder;

Notice how the argument to the constructor isn’t a Command, but an IResponder. That interface is part of the mx.rpc package that ships with Flex, and it describes two methods – result and fault. Cairngorm makes use of this interface for commands that are asynchronous, which means that they “fire and forget” calls off to the service, and expect to be called back when the service returns from the call. If you’ve been around Flex and Flash for any length of time, you know that just about everything follows this pattern of callbacks. In this case Cairngorm designed delegates to take an object that has a method, result, to callback when a service returns with a result, and fault, a method to call back if something goes wrong. It doesn’t care how that happens in the delegate or service, and the command implementing IResponder doesn’t need to know either. It just needs to know if the call worked or didn’t, and then act accordingly. The responder is set into a private property for later use.

twitteria_cairngorm/src/com/insideria/twitteria/business/TwitterDelegate.as #23-25 (formatted)

twitterService = new Twitter();
twitterService.setAuthenticationCredentials(
     model.username, model.password
);
twitterService.addEventListener(
     TwitterEvent.ON_FRIENDS_TIMELINE_RESULT,
     friendsTimelineLoaded
);

Next, the delegate creates an instance of Twitter, sets the credentials to the username and password the LoginCommand stored on the model, and registers some callbacks on the twitter service. Most times you’ll see RemoteObjects or HTTPServices inside delegates and things look a little different than you see here. RemoteObjects call AMF services, and they know how to deal with responders. Luckily though, the delegate is flexible enough to deal with our situation where we need to instantiate and set up the service right here.

Once the callbacks for each type of Twitter service call, a call of that type should call back to the method in the delegate. When we ask for the timeline, callbacks should go to the friendsTimelineLoaded method:

twitteria_cairngorm/src/com/insideria/twitteria/business/TwitterDelegate.as #49-51

private function friendsTimelineLoaded(te:TwitterEvent):void {
      responder.result(te.data as Array);
}

And that method just calls the result method on the responder with the timeline data it gets from Twitter. This is clean, because now the command doesn’t need to know anything about the Twitter class or the TwitterEvent that comes back, it just needs to know about an array of tweets that comes to the result method.

By the way there’s no fault thrown from Twitterscript, so the fault method isn’t going to ever be called, but you can imagine how it would be if there were.

Now, when the command calls loadTimeline, the delegate does this:

twitteria_cairngorm/src/com/insideria/twitteria/business/TwitterDelegate.as #29-38 (formatted)

public function loadTimeline():void {
      if (useDummyData) {
            var te:TwitterEvent = new TwitterEvent(
                 TwitterEvent.ON_FRIENDS_TIMELINE_RESULT
            );
            te.data = getDummyData();
            friendsTimelineLoaded(te);
       } else {
            twitterService.loadFriendsTimeline(model.username);
       }
}

And there’s our old friend, the dummy data. Although this still isn’t what I’d call a good way of choosing which data to load, real or fake, at least it’s all sectioned off into the delegate and no one else needs to know how it’s done. That’s called encapsulation, and just like when the delegate wraps the service, it cushions the rest of the application from change.

When LoadTimelineCommand finally gets result called, it creates a new ArrayCollection to wrap the array of tweets and places it on the model.

twitteria_cairngorm/src/com/insideria/twitteria/command/LoadTimelineCommand.as #22-25

public function result(result:Object):void {
      var stati:Array = result as Array;
      model.currentTweets = new ArrayCollection(stati);
}

That’s a very Cairngorm like sequence, there. Command calls delegate, delegate calls service, service returns to delegate (or sometimes straight to command), and then on to result, which changes something on the model. Then Flex binding takes over and modifies the view.

twitteria_cairngorm/src/com/insideria/twitteria/view/MainView.mxml #32

dataProvider="{model.currentTweets}"

Since the list in the main view is bound to the model’s currentTweets property, it will reset itself to show the new list. Slick!

Setting Status

There’s not a lot to show for setting status, since everything works pretty much the same. In fact, that’s something you can get used to with Cairngorm – if you want to know what happens because of a user interaction, find the command that gets executed and you’ll probably learn everything you need to know about what goes on. If not, you can follow back to the delegate, but the command does the bulk of the heavy lifting on the client side. Here’s SetStatusCommand’s execute:

public function execute(event:CairngormEvent):void {
      var evt:SetStatusEvent = event as SetStatusEvent;
      var delegate:TwitterDelegate = new TwitterDelegate(this);
      delegate.setStatus(evt.statusText);
}

and result:

public function result(result:Object):void {
      new LoadTimelineEvent().dispatch();
}

Notice how we have to dispatch the LoadTimelineEvent from the result? That’s one thing that some other frameworks try to work around. This command’s responsibility is telling Twitter what sweet new lolcat picture we just posted or trojan-linking in a Rick Astley video, not loading the timeline, but now we’ve tied this command up with loading the timeline. We could have had the MainView dispatch the next event if we somehow alerted the view to the fact that the status had been set, but that’s a little iffy too. In any case, the next thing that needs to happen when the status is set is to reload the timeline, so we do it here, and that’s all we need to do.

Keep that in mind for when we move on to other frameworks, because we’re out of time for today. You’ve seen how we’ve used Cairngorm’s CairngormEvents, the command pattern, delegates, and a singleton model to clean things up considerably from where we left things off last time. Next time we’ll see another framework that aims to clean some of the framework code out of the view, and rebuild our application using PureMVC.

Read more from
Tony Hillerson

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

I have moved to a different location

check out my new home Flexout

calendar

January 2009
M T W T F S S
« Dec   Feb »
 1234
567891011
12131415161718
19202122232425
262728293031  

Blog Stat

  • 83,725 Hop's so far!!!

follow me

Archives

Linkedin Blogger Twitter Youtube Orkut

Top Clicks

  • None

latest flickr photos

top rated

%d bloggers like this: