Archive

Archive for May, 2010

Flex :: Swiz 1.0rc Demo under the hood

May 21st, 2010 Michael Schmalle 1 comment

Onto another journey in the world of Flex frameworks. I was a PureMVC user until I started studying Inversion of Control systems and metadata processing. Years ago starting to learn Flex Application development one aspect that intrigued me about PureMVC was that it separated duties and was very clear what part did what. As I gained more experience with the ideas of data models, data and view controllers and service delegation my application’s classes count started to climb. PureMVC suited me for awhile but I was starting to see things that just took more time when developing an application.

I use Flex, it has strong points and fundamental design aspects that a developer can leverage for speed and for lack of a better word; simplicity. Being a component developer, I see abstractions, patterns and design decisions that will affect the overall outcome of a project’s encapsulation. I held off looking at Swiz for no other reason than my subconscious didn’t let me go there. It’s funny how these things work, your brain is almost waiting for a point where it knows it can be a clear judge of character based on your skills and understanding. I find this trait admirable in fellow developers.

Enter the Swiz framework. In this overview of the SwizeDemo by Brian Kotek, I will attempt to shed some light from the perspective of a developer wanting more and needing less (code). This article is completely from my eyes learning a framework.

To get the source code of this demo;

Swiz Framework site

Source of swizdemo_core

High Level UML of the project

swizdemo_core

Below are my abstractions of the project.

  • Configuration
  • Data Models
  • User Interface Model Presentation
  • Data & View Controls
  • Service Delegation
  • User Interface Views

Configuration <swiz:Swiz/>

Configuration in any framework is usually setup in the Application at startup. The Swiz framework is no different. The <swiz:Swiz/> tag defined in the Main.mxml application class is where this action takes place.

The application sets up three aspects of the application;

  1. config
  2. beanProviders
  3. loggingTargets

config

The config property of the Swiz instance takes an ISwizConfig instance. The SwizConfig class already implements this interface so we are ready to go.

  • eventPackages – defines where the framework looks for event classes when dispatching and handling custom events annotated by metadata.
  • viewPackages – defines where the framework looks for view classes.
  • defaultFaultHandler – A Function that will catch all application faults by default when not overridden.

beanProviders

The beanProviders Array takes a type of org.swizframework.core.IBeanProvider. The framework supplies a default implementation of this interface; BeanProvider. In a nutshell this MXML declared file instantiates;

  • UserController – Manages user service delegation (load, save, delete, delete profile) and the application’s users collection of User instances.
  • MockUserDelegate – Fakes an actual IUserDelegate implementation for offline testing and implementation (load, save, delete, delete profile). The class actually builds a mock ArrayCollection full of 4 mock User instances.
  • UserPresentationModel – A mediator for the UserContainer view’s data model and view state. This is where user interface gestures are transformed into application logic specific to it’s domain. I like this a lot, there is really no coupling to a view if this class is designed correctly. The presentation model class is a definite candidate for multiple application reuse. +1
  • ServiceHelper – A helper class in the framework to aid in IResponder creation.

loggingTargets

The loggingTargets Array takes a type of org.swizframework.utils.logging.AbstractSwizLoggingTarget. Subclasses will override logEvent() to do their custom logging. This application uses the SwizTraceTarget class which simply outputs the SwizLogEvent.message property to the console.

Data Models

The data models used in this application are;

  • User – A representation of a user with name and id.
  • UserListCollection – A collection of User instances in the application’s current session. This class subclasses the ListCollectionView and adds contain and find query methods on the collection.

User Interface Model Presentation

The user interface model presentation used in this application is;

  • UserPresentationModel – Holds the Swiz application dispatcher, the currentState of the presentation and the currentItem (User) in the presentation.

Some things to note;

Control

  • The presentation model is usually bound loosely to a controller by events. In this case the contract is between the UserPresentationModel and the UserController.
  • The UserController listens for the;
    • UserEvent.USER_SAVE_REQUESTED event
    • UserEvent.USER_DELETE_REQUESTED event
  • The two events above are dispatched through the UserPresentationModel‘s saveUser() and deleteUser() public methods, called by the presenting view (UserContainer).
  • When the UserController has delegated and received status results from either operation, it will then dispatch the;
    • UserEvent.USER_SAVE_COMPLETE event
    • UserEvent.USER_DELETE_PROCESS_COMPLETE event
  • As you can see this completes a cycle of request, delegation, operation and result asynchronously.

View State

The currentState of the view presentation is also managed by this class. The view contains the following states;

  • BASE_STATE – "" – shows only a list of users
  • DETAIL_STATE – "detail" – shows a list of users and the UserDetail view
  • EDIT_STATE – "edit" – shows a list of users and the UserForm view

The presentation model is responsible for changing the state of the view based on certain criteria;

  • When setCurrentItem() is called with a User instance and state, the presentation changes state based on the state passed to the method.
  • When setCurrentItem() is called with just a User instance, the presentation is switched into the DETAIL_STATE.
  • When setCurrentItem() is called with a null User instance, the presentation is switched to the BASE_STATE. (in the case of a cancelEdit() call with no currentItem referenced)

After any of these possibilities are met, the presentation model dispatches a CURRENT_ITEM_CHANGED event .

When a saveUser() is called and returns successfully, the presentation model will handle that event and call setCurrentItem(user) to put the view into the DETAIL_STATE. This means, you click save user, the application runs and then suddenly you see the user’s detail popup that you just saved.

When deleteUser() is called and returns successfully, the presentation model will handle that event and call setCurrentItem(null) to put the view into the

Data & View Controls

If events were wires, controllers would be circuit boards. The controllers in a Swiz application;

  • Have a public API (usually methods)
  • Use the [Mediate] metadata to wire an event into the board (controller’s public API). So here is a parrallel with event to public controller method.
  • Hold control domain specific model (only data relevant to the controller’s duty).
  • Communicate with the application’s service delegates. (IUserDelegate)

Don’t get confused here, the UserController in no way "controls" the view’s state, this is where the presentation model comes into place. The controller will dispatch complete events that could eventually change the view state, but that is ultimately up to the presentation model (UserPresentationModel) and how it implements the complete event responses.

The UserController is also responsible for passing action to service delegation and will listen for it’s response. The UserController will call the IUserDelegate API through the userDelegate defined in the Beans configuration.

On a side note; see the deleteUser() method for a nice example of asynchronous command chaining with a COMPLETE handler. This simply means;

  • Call an IUserDelegate method
  • Handle response
  • Call an IUserDelegate method
  • Handle respone
  • Handle complete

Service Delegation

Services in an application are basically ways to get something. Be it a User, an image, whatever, the service knows how to get it. The application uses the IUserDelegate interface to create a service contract. The interface says;

  • Know how to get me a list of Users - loadUsers()
  • Know how to save user information based on User data I give you - saveUser()
  • Know how to remove a user by User data I give you – deleteUser()
  • Know hot to remove a user image by User data I give you – deleteUserProfileImage()

If you create a class that satisfies all of the above requirements, congratulations, you just created a new user service that upholds the IUserDelegate contract. Your in business!

A slice of majik

In Swiz there is a lot of behind the scenes things happening, this is one area in a service oriented application that could save you a lot of time! Remember in the Beans implementation it provided a MockUserDelegate instance and called it userDelegate. The majik happens when you use the [Inject] meta above a variable that is type IUserDelegate. That instance found in the Beans will be Injected into the UserController when the controller is instantiated.

Think about this, if we are using a mock delegate to give fake user data for testing, there is only one line of code to change to hook up a real user service (implements IUserDelegate as well) that talks to a real server. You could also make the application much smarter where you wouldn’t even have to change anything, it knowing it’s in debug verses production.

User Interface Views

Finally we arrive at the view. From an application perspective this is really the least important area to "get it right". User interface design is an art and designers wear different hats. An application developer/architect needs to get it right since the user interface’s view depends on what the application domain needs to present. Classic example of this is a List versed a TileList. What is the difference? The way the underlying data is presented to the user. There should be no special treatment for either case, the data model should be complete, allow for filtering and sorting.

Where this line gets skewed a little is user interface components or UIComponents. These guys and girls lay in the middle of logic and the view. They have just enough logic to make them smart enough to do some specialized things in an encapsulated way (public API). But are dumb enough to be reused inside an actual application view.

The application uses the following views;

  • UserContainer
  • UserDetail
  • UserForm

UserContainer

The UserContainer view couples itself with the UserPresentationModel through events as discussed earlier. The UserContainer knows about the UserPresentationModel's public API and this is it. The view has no other outside knowledge of anything which creates great encapsulation. As mention before, if you can create a nice tight public API between the view and presentation model, these can be reused in other applications if needed.

The UserContainer holds one instance each of the UserDetail and UserForm views. The only things these two sub views know about is the User API and that is it. With applications designed well, you will notice a pattern; The farther into the display list you go the less a view should know (kind of rhymes :) ).

The UserContainer is also responsible for defining those view states mentioned earlier.

  • default
  • detail
  • edit

You will notice that the UserDetail declares includeIn="detail" and the UserForm declares includeIn="edit". The Flex compiler magically creates state overrides behind the scenes for the MXML properties. So when the state is detail, the UserDetail is added to the display list and the UserForm is removed, thus firing the added event that will trigger the addedEffect. Vice versa with the UserForm in the edit state.

Conclusion

Well this was a long article, I hope I help some out there. If anybody sees miss-information, let me know, I will update it.

I have a couple projects that I am going to use this framework for, keep an eye on my blog for more articles and Swiz examples.

Mike

Categories: Uncategorized Tags:

Flex Spark Product Release: VerticalMenu Widget 1.x

May 18th, 2010 Michael Schmalle No comments

The VerticalMenu Widget 1.x is now released and available for purchase.

The VerticalMenu allows the developer to arrange menus in a list fashion while allowing menus to be expanded and collapsed. The menu also acts as a toggle list where only one list item in the menu may be selected at one time.

The VerticalMenu also allows for 100% custom skinning of all parts; the menu’s main skin, header renderer and list item renders.

Check it out! VerticalMenu Product Page

Mike

Categories: Uncategorized Tags: , ,

Flex 4 :: Spark :: DockBar open source component

May 14th, 2010 Michael Schmalle 2 comments

Hello,

Teoti Graphix, LLC offers another open source component for those who wish to dive into the new Flex 4 Spark framework.

The DockBar component could be considered cliche like, um well reflections on images but, this component shows you a lot about the inner workings of a Flex 4 Spark component.

DockBar01

One aspect that makes this bar a little different is it’s parented by the systemManager and allows for 4 placements, top, right, bottom and left. It also has a property that will autoHide the bar and show it when the autoHide thickness is reached around the edge of the screen.

The component uses a Rectangle mouseMove calculation so there is no display object getting in the way of mouse events underneath the hit area.

Comments & Criticism always welcome.

Tips to look for;

  • IDockBar interface for polymorphism in an alternate implementation.
  • ButtonBarBase subclass shows how to override some common ListBase methods.
  • A default itemRendererFunction.
  • systemManager child list usage.
  • Application popup layout logic.
  • Hit Rectangle hide/show logic.
  • Use of ui.common vertical and horizontal ButtonBarLayout.

Functionality;

  • Custom DockBarSkin.
  • Custom DockBarButtonSkin.
  • DataGroup in bar with vertical and horizontal layout.
  • rollOver and rollOut skin part itemRenderer effects.
  • autoHide – constantly show the bar or hide it until the mouse is within a correct show distance.

The Code

<fx:Declarations>
	<s:Fade id="showEffect" alphaFrom="0" alphaTo="1" />
	<s:Fade id="hideEffect" alphaFrom="1" alphaTo="0" />
</fx:Declarations>
 
<components:DockBar id="dockBar" 
					skinClass="org.teotigraphix.ui.skins.DockBarSkin"
					autoHideThickness="10"
					showEffect="{showEffect}"
					hideEffect="{hideEffect}"
					change="dockBar_changeHandler(event)">
 
	<components:dataProvider>
 
		<s:ArrayList>
			<fx:Object label="One" toolTip="ToolTip One" icon="{theIcon}"/>
			<fx:Object label="Two" toolTip="ToolTip Two" icon="{theIcon}"/>
			<fx:Object label="Three" toolTip="ToolTip Three" icon="{theIcon}"/>
			<fx:Object label="Four" toolTip="ToolTip Four" icon="{theIcon}"/>
		</s:ArrayList>
 
	</components:dataProvider>
 
</components:DockBar>

When the application starts up, the dock bar is removed from Application and added to the systemManager.

The library ui.common;

Sample MXML

I have not uploaded a new zip distro yet with this component available.

Bugs

There are still some issues with effects and the zoom effect glitching once and awhile.

I’m also working on a build file that will add all of the examples into the ui.common.zip distribution file. So when you download the zip library, there will be a Flash Builder project ready to test out like a turnkey.

Mike

Spark ComboBox textRollOverColor

May 11th, 2010 Michael Schmalle No comments

The transition from halo to spark has blurred the lines of what a developer in Flex 3 thinks they can do with styles in Flex 4.

Here is an example of creating an itemRenderer with a textRollOverColor and textSelectedColor styles (known in Flex 3).

Spark ComboBox textRollOverColor01

We have some components that will be released in our open source Spark framework that addresses some of these issues. Pre-made itemRenderers, abstracted styles for the developers that still want some style control.

http://teotios.googlecode.com

The application needs to define the styles for the ComboBox and set it’s itemRenderer to the new enhanced renderer.

Application.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
               xmlns:s="library://ns.adobe.com/flex/spark" 
               xmlns:mx="library://ns.adobe.com/flex/mx">
 
 
    <fx:Style>
        @namespace s "library://ns.adobe.com/flex/spark";
        @namespace mx "library://ns.adobe.com/flex/mx";
 
        s|ComboBox
        {
            textRollOverColor:#FF0000;
            textSelectedColor:#FFFFFF;
        }
 
    </fx:Style>    
 
    <!-- 
    The ComboBox renders it's data elements with the
    provided item renderer. 
    -->
    <s:ComboBox itemRenderer="MyItemRenderer"
                horizontalCenter="0" top="10">
        <s:dataProvider>
            <s:ArrayList>
                <fx:String>One</fx:String>
                <fx:String>Two</fx:String>
                <fx:String>Three</fx:String>
                <fx:String>Four</fx:String>
            </s:ArrayList>
        </s:dataProvider>
    </s:ComboBox>
 
</s:Application>

Subclass the ItemRenderer class in MXML to create the data’s visual appearance.

We implement the states expected by ItemRenderer and use getStyle() to retrieve the correct style values.

Note the autoDrawBackground, Adobe added this property right before Flex 4 was released. This took out the mandatory normal, hover and selected backgrounds. Now this drawing is natively supported in the ItemRenderer class.

MyItemRenderer.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009" 
                xmlns:s="library://ns.adobe.com/flex/spark" 
                xmlns:mx="library://ns.adobe.com/flex/mx" 
                autoDrawBackground="true">
 
    <!-- Declare the states the ItemRenderer super class needs. -->
    <s:states>
        <s:State name="normal"/>
        <s:State name="hovered"/>
        <s:State name="selected"/>
        <s:State name="normalAndShowsCaret"/>
        <s:State name="hoveredAndShowsCaret"/>
        <s:State name="selectedAndShowsCaret"/>
    </s:states>
 
    <!-- 
    The default implementation of the ItemRenderer uses the data
    property to pass the item's data item.
    Use getStyle() to retrieve any style set in the parent's style chain.
    -->
    <s:Label text="{data}" 
             color.hovered="{getStyle('textRollOverColor')}"
             color.selectedAndShowsCaret="{getStyle('textSelectedColor')}"
             top="5" right="5" bottom="5" left="5"/>
 
</s:ItemRenderer>

Mike

Categories: tutorials Tags: