Wednesday, May 30, 2007

Flex/Cairngorm Tips: #1

So I thought it might be cool to pass along some tips/tricks that got me through the development on SeeSpotSlide. I'll be posting these as I run across them in my head or through updates to the application.

Using a Model to Control the View
I started doing this about half way through the development of the application after seeing it done in some sample apps on a Cairngorm message board. The gist of it is that you tie a component's view to a model. You change the model from anywhere in the application and the view changes. Simple right?!

Here's some sample from the SeeSpotSlide codebase:
In my model classes I have one called ViewModel.as. It is a singleton class (only one instance can exist at a time) and has the following structure.

package com.model
{
import com.adobe.cairngorm.model.ModelLocator;
import com.model.ViewModel;

public class ViewModel implements ModelLocator
{
private static var model:ViewModel;

[Bindable]
public var viewStateReports:Number = VIEW_GRAPHS;
public static var VIEW_GRAPHS:Number = 0;
public static var VIEW_GRID:Number = 1;


public function ViewModel()
{
if (model != null)
throw new Error("only one ViewModel instance should exist");
}

public static function getInstance():ViewModel
{
if (model == null)
{
model = new ViewModel();
}

return model;
}
}
}


Then, in my view class I bind to 'viewStateReports' on say an accordion component like this:
<mx:accordion id="myStuff_acc"
width="560" x="10" bottom="125" top="53"
selectedIndex="{ ViewModel.getInstance().viewStateReports }" />

Now, from any class file I can instantiate the instance of the ViewModel class and change the state of 'viewStateReports' like this:
ViewModel.getInstance().viewStateReports = ViewModel.VIEW_GRID

My accordion component updates due to it's binding to the model. No crazy paths to follow to point back to the component and no custom events that need to be built and fired to trigger the change. The binding mechanism on the accordion sets up it's built in event listeners to make the change. It's probably a good idea to come up with a naming convention that is really obvious here on the 'states' you'll be changing to. When you have a bunch of states of components and views changing in this way, things can get a bit hairy without a solid naming strategy.

No comments: