Cairngorm Getting Started Part Four : Events, Commands and Controllers

Wednesday, 30. July 2008 15:20 | Author:admin

So we’ve had a chat about the MVC design pattern and how that relates to Cairngorm, set up the environment and we’ve discussed how Singletons work.  Now we are ready to start using the framework to create a basic application.

Frameworks like Cairngorm really come into their own when you are creating a large or relatively complicated application.  For the purposes of this little demonstration we will load an XML file and display it in either a Tree component or in a TextArea component.  No great shakes and I know that if this was all you really needed to to then using Cairngorm is a little bit of an overkill, but keeping it simple means we’ll clearly be able to look at what the framework does without having to go over lots of code.

To just go back a step for a moment we are going to quickly recap how the Cairngorm framework operates.

The view dispatches events to the controller.  The controller then either modifies the model directly or in the case of getting some data, creates a delegate and a responder.  The delegate gets the data and returns it to the responder that modifies the model.  Then the model tells the view what to display.

Ideally each set of classes should only operate in an expected way on the other classes.  IE the models should only ever be modified by Controllers or Responders, the Delegates should be the only classes that get data, the views should only do view stuff.  This is the delegation of responsibility.

Lots of books and tutorials almost talk about classes as if they are sentient beings, the view shouldn’t know about the model, the model shouldn’t know about the controller.  This sort of worked for me, but I can’t really anthropomorphise what I know is just a set of classes.

Another way of looking at this, and one which makes sense to me, is that it’s all about organisation.  You wouldn’t file your car tax in the fridge, otherwise you’ll spend ages looking for it when you need to renew it.  Likewise with a Cairngorm app if something is wrong with the data call you know to start at the Delegate and see what is happening there.  (If you wanted a new car you wouldn’t want to have to change the fride too.  This analogy doesn’t quite hold up, but you know what I mean).

So if we’re happy with that lets get on with the code.

We’ll start first with the base mxml application file.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application layout="vertical">

<mx:Script>
<![CDATA[
]]>
</mx:Script>

<mx:Panel title="XML Display" width="600" height="500">
<mx:ViewStack width="100%" height="100%">
<mx:Box>
<mx:Tree/>
</mx:Box>
<mx:Box>
<mx:TextArea/>
</mx:Box>
</mx:ViewStack>
<mx:ControlBar>
<mx:Button id="btn_tree" label="Display as Tree"/>
<mx:Button id="btn_datagrid" label="Display as TextArea"/>
</mx:ControlBar>
</mx:Panel>

</mx:Application>

Nice and simple.  So first things first we need to get the XML.  I’ve created a very very simple XML file.

<?xml version="1.0" encoding="utf-8"?>
<exampleXML>
<block title="Block One">
<item name="Item One"/>
<item name="Item Two"/>
<item name="Item Three"/>
<item name="Item Four"/>
</block>
<block title="Block Two">
<item name="Item One"/>
<item name="Item Two"/>
<item name="Item Three"/>
<item name="Item Four"/>
<item name="Item Five"/>
<item name="Item Six"/>
<item name="Item Seven"/>
</block>
<block title="Block Three">
<item name="Item One"/>
<item name="Item Two"/>
<item name="Item Three"/>
<item name="Item Four"/>
<item name="Item Five"/>
<item name="Item Six"/>
</block>
<block title="Block Four">
<item name="Item One"/>
<item name="Item Two"/>
<item name="Item Three"/>
<item name="Item Four"/>
<item name="Item Five"/>
<item name="Item Six"/>
<item name="Item Seven"/>
<item name="Item Eight"/>
<item name="Item Nine"/>
<item name="Item Ten"/>
<item name="Item Eleven"/>
<item name="Item Twelve"/>
</block>
<block title="Block Five">
<item name="Item One"/>
<item name="Item Two"/>
<item name="Item Three"/>
<item name="Item Four"/>
</block>
<block title="Block Six">
<item name="Item One"/>
<item name="Item Two"/>
<item name="Item Three"/>
<item name="Item Four"/>
<item name="Item Five"/>
<item name="Item Six"/>
</block>
</exampleXML>

To trigger the load we’ll need to dispatch an event.  This is a very simple event so it’ll be a very simple class.  I’ve called it LoadXMLEvent and it’s saved in the event folder we created in part Two.  Right click on the folder, select new class.  When the class wizard launches we need to extend the CairngormEvent class.  Select the browse button next to the Superclass text input and then start to type ‘CairngormEvent’ into the panel that pops up.  It’ll quickly find CairngormEvent, click OK and then OK again into the wizard panel.  This will generate the class with the correct imports and will also create the constructor for you.

Like I said this is a very simple class, it doesn’t need to even parse any data, all we want to do is announce we need the XML.

package com.worthyashes.simpleCairngorm.events
{
import com.adobe.cairngorm.control.CairngormEvent;

import flash.events.Event;

public class LoadXMLEvent extends CairngormEvent
{
public static const LOAD_XML_EVENT:String = "loadXMLEvent";

public function LoadXMLEvent(bubbles:Boolean=false, cancelable:Boolean=false)
{
super(LOAD_XML_EVENT, bubbles, cancelable);
}

override public function clone():Event
{
return new LoadXMLEvent(this.bubbles,this.cancelable);
}

}
}

Lets go through the code.  The first variable is a public static constant variable (it’s in capitals as a visual indication that it is a constant, this is not necessary though it is a convention worth following.)

All this really does is hold the string to indicate what event this class is.  CairngormEvents exetend the standard Event class so it requires a string indicator.  Rather than parseing the name of the event in when the event is created by the class using it we are it in the class so we have more control, and access to it through the static variable.  This means that we don’t have to try and remember what we called this event, if we need to access this name all we need to do is use LoadXMLEvent.LOAD_XML_EVENT, and we make sure that we are talking about the correct event.

Now for the constructor.  As we are not parseing any data we don’t really have to put anything in the constructor, but as it’s best practice (and the code was written for us) we’ll leave the variables for bubbling and canceleable in.

Note that in the super() function, that calls the Superclasses constructor we are parsing the LOAD_XML_EVENT variable in to type the class.

Finally we override the clone function.  This function is used for bubbling and by overriding this function we make sure the correct event type is returned.

That’s it – our first CairngormEvent, woo hoo!

Next we’ll create the Controller that’ll actually do something.

On the commands folder right click, select new , class and then in the wizard rather than selecting a superclass we are going to select an interface.  The ICommand interface types this class as an ICommand and also defines the functions required by it.

Select the add button next to the Interface text area, start typing in ICommand and when it finds the correct interface select it and hit OK.  Select OK on the wizard panel and your controller will be created with all of the required imports and also the required functions to satisfy the interface.

Now onto the class

package com.worthyashes.simpleCairngorm.commands
{
import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;
import com.worthyashes.simpleCairngorm.events.LoadXMLEvent;

public class LoadXMLCommand implements ICommand
{
public function LoadXMLCommand()
{
}

public function execute(event:CairngormEvent):void
{
var e:LoadXMLEvent = event as LoadXMLEvent;

trace("Load XML Event triggered the command!!");
}

}
}

All we’ve done here is populate the execute function with a trace so we know it’s working.  I also set a variable, in this case e as the Type of event that has triggered this command and cast the event passed into the function to the correct type.  In other classes this can be useful as this then gives you native access to the Event classes properties.  In this case the LoadXMLEvent has no properties, it only exists to tell the application it is time to get some XML, but I still have it there.  It’s not necessary, but after you’ve been putting together a large application you have a pile of classes, having a reference to the event class in the command class makes it easier to find.

So we’ve created an Event and we’ve created a Command – but aren’t we doing an MVC implementation?  Where’s the controller?  That comes now and the controller exists to tie the Events and Commands together.

Right click on the control folder and select new class.  This class extends FrontController and I’ve called mine SimpleFrontController.
The FrontController class listens to the CairngormEventDispatcher class and executes Commands based on the events called.

Lets add our code to start it working.

package com.worthyashes.simpleCairngorm.control
{
import com.adobe.cairngorm.control.FrontController;
import com.worthyashes.simpleCairngorm.commands.*;
import com.worthyashes.simpleCairngorm.events.*;

public class SimpleFrontController extends FrontController
{
public function SimpleFrontController()
{
super();
initialise();
}

private function initialise():void
{
addCommand(LoadXMLEvent.LOAD_XML_EVENT,LoadXMLCommand);
}

}
}

We’ve created our own initialise function and in this function we tie the commands and the events together.  Remeber the static string we created in the LoadXMLEvent class that was then passed to the super function as the type?  This is an example of why we do this – we don’t need to remember the type, all we need to do is reference the Event class itself.  This is really handy if we need to change the type – rather than picking through the app changing strings we change it in the Event class itself and that’s it.

Now we’ve created the controller we need to instantiate it.  This can be done with MXML in the application.  We’ll also trigger the event.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application layout="vertical"
xmlns:control="com.worthyashes.simpleCairngorm.control.*"
creationComplete="creationCompleteHandler();">

<mx:Script>
<![CDATA[
private function creationCompleteHandler():void
{
var loadXMLEvent:LoadXMLEvent = new LoadXMLEvent();
loadXMLEvent.dispatch();
}
]]>
</mx:Script>

<control:SimpleFrontController id="frontController"/>

<mx:Panel title="XML Display" width="600" height="500">
<mx:ViewStack width="100%" height="100%">
<mx:Box>
<mx:Tree/>
</mx:Box>
<mx:Box>
<mx:TextArea/>
</mx:Box>
</mx:ViewStack>
<mx:ControlBar>
<mx:Button id="btn_tree" label="Display as Tree"/>
<mx:Button id="btn_datagrid" label="Display as TextArea"/>
</mx:ControlBar>
</mx:Panel>

</mx:Application>

What have we added?  First of all we’ve added an xmlns attibute to the main application tag.  This allows us to shortcut accessing the controller by using our own name ‘control’ that will reference the com.worthyashes.simpleCairngorm.control package.  We’ve also added a creation complete handler function for the creationComplete event.  This function creates and dispatches an loadXMLEvent.  Finally we’ve added the FrontController using MXML.  Run it and you will get the trace from the Command class as it executes – don’t forget to debug the application rather than running it.  Next we are going to look at the Delegate that retrieves the data and introduce a new class, the ServiceLocator class.

Category:Cairngorm, Flex, Frameworks, Tutorials | Comments (1)

Fixed for IE 7

Wednesday, 30. July 2008 9:06 | Author:admin

That’ll do for now…..

Category:Uncategorized | Comment (0)

Blog not rendering properly in IE

Wednesday, 30. July 2008 8:52 | Author:admin

Sorry – I just realised……. Will fix soon as!

Category:Uncategorized | Comment (0)

Linux – Unbreakable……..

Thursday, 24. July 2008 16:34 | Author:admin

…..or is it?

Completely forgot that I had this picture.  I got this little Linux Penguin squeezy figure at a conference, and Charlie took a shine to it.  He was happily playing away with the penguin and then I turned my back for a second and this act of vandalism was committed.  Mind you it did say unbreakable……

Unbreakable Linux

Category:Just For Fun | Comment (0)

Clearing the Standalone Flash Player cache

Wednesday, 23. July 2008 14:44 | Author:admin

I’m putting together a video player and I wanted to test the scrubber (the little button you use to drag the playback) was working.  More importantly I wanted to test it couldn’t be dragged further than the video had downloaded.  So I uploaded an flv to my site and tested the player.  This was fine the first time and then the stand alone player cached the flv, so I couldn’t test it anymore.  A quick google and I found this really handy tip.

Category:Uncategorized | Comments (1)

Last.FM gotcha?

Wednesday, 23. July 2008 9:15 | Author:admin

I’ve started using Last.fm and it is fantastic!  I was listening to some Armand Van Burien when I scrolled down to see what other people thought about it.  As I was scrolling down my mouse rolled over one of the images as i was using firefox it displayed the alt (caption) text as flyout text.  In the case of Last.fm this turns out to be a description of the users details.

Trade Description Act?

r34c7 – you are busted.

Category:Just For Fun | Comment (0)

My SWC isn’t Compiling properly!

Friday, 4. July 2008 9:42 | Author:admin

Had this quick gotcha the other day with flex builder and I thought I’d share – mainly for myself as I’ll no doubt forget this before too long.

I was working on a Flex Library Project.  Really cool you can work on classes in the Library project and as you save them they are compiled into a SWC file in the bin directory (as long as you have Build Automatically checked in the Project Menu, that’s another gotcha that drove me made for a bit when I turned it off as I was working on a large app and couldn’t be arsed to wait the 5 mins after each save whilst the compiler built the project.  Forgetting to turn it on or build the project gave me heartfailure when I launched the swf to test it was working.)  Anyway – back to Flex Library Projects generating SWCs.  Nice.  I can then share this, or just link to it and speed stuff up by using common code.

However I’d just added another folder and a few more classes to the Library project, saved them and then went off to the flex app I was building and started coding happily away.  Rather quickly I realised I wasn’t picking up the new classes I’d added to the SWC.  I checked in the Library Project, they were there.  I saved them again – thinking that sometimes maybe the SWC doesn’t compile.  I checked that Build Automatically was turned on (see above) it was.  I deleted the SWC and resaved the new classes.  Nothing happened.  Shit – I must have corrupeted somehow!  I decided to check on of the original classes – all fine, I saved it again and – hang on – there’s the SWC.  All compiled lovely.  Great!  Back to the flex app.

Nope – it still hasn’t compiled the new classes and packages into it and I have no access.  Right now I’m ready to throw the computer out of the window when I right click on the Library project, select Properties and then Flex Library Build Path.  Aha.  Even though I’ve added files and folders they ARE NOT added to the build path.  Click on them to select them, save – and there we go.  All sorted.

So long story short – if you’re compiling a swc using a Flex Library project and it’s missing packages and classes you know should be there, check the build path.

P.S.  I think I may be going bald with all the hair I’ve pulled out.

Category:Flex Builder Gotchas | Comments (2)

Errrr……Where do you normally keep your lighter?

Friday, 4. July 2008 8:47 | Author:admin

Ok, this morning on the way to work I stopped at my normal coffee place, grabbed my coffee and sat outside so i could have a ciggarette and wake up before a hard days coding (note that employers – a HARD DAY’s CODING).

I was watching the world go by and enjoying the Diggnation podcast when a deliver truck pulled up.  The blokie driving got out and walked round to the back smoking a fag himself (note to American readers this mean having a ciggarette, not shooting someone who’s made a different lifestyle choice) and when he got round to the back of the van he pocked the half smoked ciggarette up the exhast pipe for later while he made the delivery.  OK, I suppose it wasn’t high tar enough.  However the next bit really confused me – to make clear this guy was a normal bloke, wearing normal clothes, I’m pointing this out so you understand he had pockets.  He had his lighter in his hand.  Obviously like the ciggarette he needed to put it somewhere so he could load up the little trolley for his delivery.  So he stuck it in his shoe.  Not down the side next to his foot, in the sole…….. What sort of mental gymnastics do you make to decide that this is logically the best place to put it, bypassing all pockets on the way down?

Anyway – thought I’d share.

(Also had a wierd dream that Tor (the wife) died Charlie’s (the baby) hair and it all fell out.  It’s been a strange start to a Friday)

Category:Uncategorized | Comment (0)

Cairngorm Getting Started Part Three : Singletons

Wednesday, 2. July 2008 22:07 | Author:admin

We’ve covered an overview of the MVC pattern and how it relates to Cairngorm and we’ve set up the environment and we’ve set up the environment so we can finally start to play with some code.  Nearly.

There is one last concept to go over before we move on, Singletons,  I’m sure that most of you are happy with this concept, but for those who don’t here we go.

A singleton is a class that there can only be one of.  Ever.  To borrow a joke from someone else – like Highlander there can be only one (though this analogy doesn’t quite add up as initially there were loads of them, then they had to fight each other to whittle the numbers down to one.  However the sequals made a mockerly of this idea as ‘aliens’ got involved in a typical WTF can we do now idea to make more money out of this clearly dead horse – and ruined a fantastic film.  So to relate this to a design pattern is actually quite misleading.) (Don’t get me started on the Matrix sequals – he had clearly won at the end of the first one, why didn’t you stop there?)

Right, sorry I do tend to digress a bit (Star Wars prequals!  WTF were they all about?  On a side note when I was an actor in the London Dungeon, long story but safe to say the acting career when fantastically well :( , I actually made the little boy who played Anakin Skywalker cry.  So I made Darth Vader cry – sort of.  Beat that!)

I did it again, concentrate – back to singletons.  Like I said a singleton is a class that there can be only one of.  Why is this helpful?  Well if there is only one then everytime you access the class you have exactly the same data stored within t.  They can be thought of as silos of data, or memory.  They can also be bound to view components and this is where the concept of changing the model to change the view works.  This is why they are used as a major part of the Cairngorm framework.  (Lots of people don’t like singletons, and I’m still not entirely sure why)

Here is an example of a Cairngorm singleton : -

package com.worthyashes.simpleCairngorm.model
{
        import com.adobe.cairngorm.model.IModelLocator;
        [Bindable]
        public class MemoryModelLocator implements IModelLocator
        {
         //Singleton code
         private static var _instance:MemoryModelLocator;

         public function MemoryModelLocator(enforcer:SingletonEnforcer)
         {
         if (enforcer == null)
             {
              throw new Error("Like at the end of Highlander, before the crap sequal, there can be only one");
             }
         }

          public static function getInstance():MemoryModelLocator
          {
           if (_instance == null)
            {
                _instance = new MemoryModelLocator(new SingletonEnforcer());
              }
            return _instance;
            }
            //End of singleton code

           //Pop your vars into the model from here on
      }
}
class SingletonEnforcer{}

Lets go through the code

[Bindable]

public class MemoryModelLocator implements IModelLocator

The [Bindable] keyword makes this class available for flex bindings so it is possible to directly bind the ModelLoactor and it’s subsequent variables to the view components as discussed above.

A Cairngorm Singleton is also known as a ModelLoactor and implements the IModelLocator interface. (For a discussion of interfaces you’re going to have to do a bit of a google.  I understand them, understand how and why to use them, but for the life of me I can’t actually put into words why – I’ll have a go at a later post)

Now for the slightly mind bending bit, once you’ve got the hang of this it will all become clear.

private static var _instance:MemoryModelLocator;

This variable _instance, the underscore is there to indicate it is a private variable (the private keyword does that really, the underscore is more a visual reminder in the code), holds a reference to the MemoryModelLocator class.  Which is the class that it is in.  So it holds a reference to itself, in itself.  Which you’d imagine would have another _instance variable, but the keyword static indicates that this variable is always the same in every single instance of this class.  So every time you access the Singleton after it has initially been instantiated you are getting the same class back.  I’ve just re-read that, I think it makes sense – if not then send me a mail and I’ll re-work that paragraph.

Now onto the constructor.  In order for a singleton to work we need to only ever create one at any time.  This means we DON’T want to be able to call the constructor directly, as this would instantiate a new class.  By convention we call a static function called getInstance() (It doesn’t have to be called this, but as it’s a convention I recommend you stick to it) that returns an instance of the class.

Singletons in AS2 were easier to do.  This was because it was allowed to create a class and set the constructor to be private.  So you’d write something like : -

private function MemoryModelLocator()
{
}

However you can’t do this in AS3.  So we have a hack.  The Cairngorm team have acknowledged it as a hack, so I’ll say it too, hack, hack, hack.  To understand how this hack works we need to look at the new package structure of AS3.  In this case : -

package com.worthyashes.simpleCairngorm.model
{
//The class goes in here
}

Now if I put another class in this package (folder) I would be able to instantiate the MemoryModelLocator class without importing it and use the functions within it.  I could create an instance of the class without any bother at all, and we want to stop this.  So we create a class outside the package declaration.

//End of class
}
class SingletonEnforcer{}

This class is outside the curly brackets that close off the package, and is not available to ANY class except for the MemoryModelLocator class.

So if we pop an instance of this Singleton enforcer class into the constructor of the MemoryModelLocator class then we can force the MemoryModelLocator class to only ever be instantiated by itself through the getInstance() function.

So the constructior is : -

public function MemoryModelLocator(enforcer:SingletonEnforcer)
{
if (enforcer == null)
{
throw new Error("Like at the end of Highlander, before the crap sequal, there can be only one");
}
}

and the getInstance() function looks like this.

public static function getInstance():MemoryModelLocator
{
if (_instance == null)
{
_instance = new MemoryModelLocator(new SingletonEnforcer());
}
return _instance;
}

To go through this and explain it, remember that the _instance variable is static and therefore will be the same every time this class is accessed.  What we do with the getInstance() call is to first of all check if the _instance variable exists.  If not then we create it by calling the constructor with an instance of the SingletonEnforcer class.  This can be accessed by the getInstance() function as it is in the MemoryModelLocator class.  Then we return the _instance variable.  So if we make the call to the getInstance() function in the MemoryModelLocator we will ALWAYS get the same Singleton.  As it is a static function (which it has to be so we can call it and return a static variable) we use it slightly differently, like this : -

var model:MemoryModelLocator = MemoryModelLocator.getInstance();

Right – hopefully that all made sense.  It’s a bit confusing, but hopefully once you see the ModelLocator in action it’ll all be made clear!

Category:Cairngorm, Flex, Frameworks, Tutorials | Comments (2)

Papervision 3D for ActionScript 2

Thursday, 26. June 2008 14:40 | Author:admin

OK – so they forgot to tell me it was for flash player 8.  Oh well.  So I’ve done it for ActionScript 2 with some controls for testing.

Papervision 3d AS2

Have fun!

Category:Uncategorized | Comments (5)