<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	>

<channel>
	<title>Web App Solution Blog &#187; swiz</title>
	<atom:link href="http://www.webappsolution.com/wordpress/category/swiz/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.webappsolution.com/wordpress</link>
	<description>When you're in need of an appsolution</description>
	<pubDate>Thu, 05 Apr 2012 19:39:33 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Swiz EventHandler Filtering With Pub/Sub Topics - Part 2</title>
		<link>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/#comments</comments>
		<pubDate>Wed, 29 Dec 2010 21:15:40 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[eventhandler]]></category>

		<category><![CDATA[metadata]]></category>

		<category><![CDATA[pub-sub-topics]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=946</guid>
		<description><![CDATA[After giving my first pass at this a little thought (which gives all of the details and explains how I got here) I realized the topic value defined in the EventHandler metadata tag was essentially hardcoded and set at compile time &#8212; this can work for some situations, but obviously isn&#8217;t ideal. I then decided [...]]]></description>
			<content:encoded><![CDATA[<p>After giving <a href="http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/" target="_blank">my first pass</a> at this a little thought (which gives all of the details and explains how I got here) I realized the topic value defined in the EventHandler metadata tag was essentially hardcoded and set at compile time &#8212; this can work for some situations, but obviously isn&#8217;t ideal. I then decided I needed a way to filter events in Swiz by topics with data and values set at runtime. The event dispatching is still the same:</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch global events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;global&quot; can
 * handle this event. This means other modules and even the shell application
 * can handle this event if we want.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;global&quot;)]
public var globalDispatcher:IEventDispatcher;
...
public function sayHello():void
{
	logger.debug(&quot;sayHello&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SAY_HELLO);
	appEvt.hello = &quot;Hello World!&quot;;
    appEvt.topic = &quot;wasiTopic&quot;;
	this.globalDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>But the event handling is setup with a new, additional attribute called topicProperty. </p>
<pre class="brush: as3;">
public var myTopic:String = &quot;wasiTopic&quot;;
...
[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;, topicProperty=&quot;myTopic&quot;)]
public function helloWithTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // WORKS
}
</pre>
<p>This now allows the developer to set the member variable for the object doing the event handling at runtime. Internally in Swiz&#8217;s <code>org.swizframework.utils.event.EventHandler</code>&#8217;s method <code>public function handleEvent( event:Event ):void</code> we now look for the attribute &#8220;topic&#8221; and &#8220;topicProperty&#8221; in the EventHandler metadata. If the user has set the topicProperty, the method looks at the Bean that&#8217;s using EventHandler and inspects it for this String property and then compares it to the topic passed in the event. This requires some more changes to the Swiz class <code>org.swizframework.utils.event.EventHandler</code>.</p>
<p>Grab the changes I made to Swiz <a href="http://webappsolution.com/flex/blog/examples/swiz-eventhandling-with-topics.zip" target="_blank">here</a>.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+EventHandler+Filtering+With+Pub%2FSub+Topics+-+Part+2+http://mcawd.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+EventHandler+Filtering+With+Pub%2FSub+Topics+-+Part+2+http://mcawd.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz EventHandler Filtering With Pub/Sub Topics - Part 1</title>
		<link>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/#comments</comments>
		<pubDate>Wed, 29 Dec 2010 18:47:22 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[eventhandler]]></category>

		<category><![CDATA[filtering]]></category>

		<category><![CDATA[metatadata]]></category>

		<category><![CDATA[pub-sub-topics]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=930</guid>
		<description><![CDATA[We tend to build many Flex applications with modules, so having the ability to broadcast and listen for messages based on the scope attribute for both Dispatchers and EventHandlers is essential in Swiz. 
UPDATE: Part 2 has Swiz framework code changes and a more robust solution.
If you don&#8217;t know about Swiz Event Scoping, then read [...]]]></description>
			<content:encoded><![CDATA[<p>We tend to build many Flex applications with modules, so having the ability to broadcast and listen for messages based on the <a href="http://swizframework.jira.com/wiki/display/SWIZ/Module+Support" target="_blank">scope attribute for both Dispatchers and EventHandlers is essential in Swiz</a>. </p>
<p>UPDATE: <a href="http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/" target="_blank">Part 2</a> has Swiz framework code changes and a more robust solution.</p>
<p>If you don&#8217;t know about Swiz Event Scoping, then read on; otherwise, skip to the section labeled <a href="#topics">Filtering With Topics below</a>.</p>
<p><strong>Background</strong></p>
<p>You can read the actual documentation from Swiz in the last link, but the gist is that you can tell Swiz to either broadcast events on a &#8220;global&#8221; level (using the highest level Application object) or on a &#8220;local&#8221; level (using the Module itself) and then listen to those events in the same fashion. This allows you to tell modules to listen to events only from themselves and not other modules (that might have the same events) or to listen to all events from your main, shell application and/or all other modules. Let&#8217;s look at a quick example by assuming the dispatching code is in LoginViewMediator and the handling code is in LoginController in a Module.</p>
<p><strong>Local Event Dispatching</strong></p>
<p>Local Event Dispatching From LoginViewMediator</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch local events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;local&quot; can
 * handle this event.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;local&quot;)]
public var localDispatcher:IEventDispatcher;
...
public function login(userName:String, password:String):void
{
	logger.debug(&quot;login&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SERVICE_LOGIN);
	appEvt.username = userName;
	appEvt.password = password;
	this.localDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>Local Event Handling in LoginController</p>
<pre class="brush: as3;">
[EventHandler(event=&quot;AppEvent.SERVICE_LOGIN&quot;, properties=&quot;username, password&quot;, scope=&quot;local&quot;)]
public function login(username:String, password:String):void
{
	logger.debug(&quot;login: username = &quot; + username + &quot;, password = &quot; + password);
}
</pre>
<p>If we had other Modules with this same EventHandler statement in their LoginController they would not fire because we specified the scope as local. If we change the scope property to global and the AppEvent is in a common library that all Modules can use, then they would each hear this event and all fire, which in many cases is not what you want. Just so we have a full understanding of what&#8217;s going on, let&#8217;s show an example of broadcasting global events in a similar fashion:</p>
<p><strong>Global Event Dispatching</strong></p>
<p>Global Event Dispatching From ModuleA</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch global events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;global&quot; can
 * handle this event. This means other modules and even the shell application
 * can handle this event if we want.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;global&quot;)]
public var globalDispatcher:IEventDispatcher;
...
public function sayHello():void
{
	logger.debug(&quot;sayHello&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SAY_HELLO);
	appEvt.hello = &quot;Hello World!&quot;;
	this.globalDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>Global Event Handling in Module B</p>
<pre class="brush: as3;">
[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;)]
public function hello(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello);
}
</pre>
<p><a name="topics"><strong>Filtering With Topics</strong></a></p>
<p>Again, this is awesome&#8230;but what if you want to broadcast a message that you only want some of the modules to hear? You could obviously put in some simple logic in the event handler that determines if your Module was supposed to listen to the event based on a parameter passed in the EventHandler MetaData, but this could potentially become a large and unwieldy task that you&#8217;ll need to apply to all new modules&#8230;so what if we introduce filtering of Swiz events via a topic attribute in the EventHandler metadata and a corresponding topic property in our dispatched event?</p>
<p>To do this, we&#8217;ll need to do some quick monkey patching to Swiz (by creating the same package structure and adding the same classes we want to change that exist in the Swiz SWC). First, let&#8217;s add the topic property to the <code>org.swizframework.metadata.EventHandlerMetadataTag</code>. Add the topic property:</p>
<pre class="brush: as3;">
protected var _topic:String;
public function get topic():String
{
	return _topic;
}
</pre>
<p>Then add the following to the method <code>override public function copyFrom( metadataTag:IMetadataTag ):void</code></p>
<pre class="brush: as3;">
if( hasArg( &quot;topic&quot; ) )
    _topic = getArg( &quot;topic&quot; ).value;
</pre>
<p>Next we&#8217;ll edit the method <code>public function handleEvent( event:Event ):void</code> in <code>org.swizframework.utils.event.EventHandler</code>. Add the following right after the first if() statement:</p>
<pre class="brush: as3;">
// look for a topic -- if the one exists in the EventHandler MeataData and
// the event does not have one or the value does not equal the EventHandler's
// then we'll filter out this event and not allow it
if(metadataTag.topic != null)
{
	if(event[&quot;topic&quot;] == null)
	{
		return;
	}
	else if(event[&quot;topic&quot;] != metadataTag.topic)
	{
		return;
	}
}
</pre>
<p>That&#8217;s it. Let&#8217;s give it a whirl by using a global dispatcher again, but adding a topic property to the event and a topic attribute to the EventHandler metadata.</p>
<p>Global Event Dispatching From ModuleA</p>
<pre class="brush: as3;">
/**
 * Allows this class to dispatch global events. Only methods using an
 * EventHandler metatadata tag with the property of scope=&quot;global&quot; can
 * handle this event. This means other modules and even the shell application
 * can handle this event if we want.
 *
 * &lt;p&gt;
 * The event dispatcher is injected by Swiz due to the [Dispatcher] metadata
 * and the class member's type of IEventDispatcher.
 * &lt;/p&gt;
 */
[Dispatcher(scope=&quot;global&quot;)]
public var globalDispatcher:IEventDispatcher;
...
public function sayHello():void
{
	logger.debug(&quot;sayHello&quot;);

	var appEvt:AppEvent;

	appEvt = new AppEvent(AppEvent.SAY_HELLO);
	appEvt.hello = &quot;Hello World!&quot;;
        appEvt.topic = &quot;wasiTopic&quot;;
	this.globalDispatcher.dispatchEvent(appEvt);
}
</pre>
<p>Global Event Handling in Module B</p>
<pre class="brush: as3;">
[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;, topic=&quot;wasiTopic&quot;)]
public function helloWithTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // WORKS
}

[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;)]
public function helloWithOutTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // NOPE
}

[EventHandler(event=&quot;AppEvent.SAY_HELLO&quot;, properties=&quot;hello&quot;, scope=&quot;global&quot;, topic=&quot;fooTopic&quot;)]
public function helloWithOutTopic(hello:String):void
{
	logger.debug(&quot;hello = &quot; + hello); // NOPE
}
</pre>
<p>UPDATE: <a href="http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics-part-2/" target="_blank">Part 2</a> has Swiz framework code changes and a more robust solution.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+EventHandler+Filtering+With+Pub%2FSub+Topics+-+Part+1+http://wzsfn.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+EventHandler+Filtering+With+Pub%2FSub+Topics+-+Part+1+http://wzsfn.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/12/29/swiz-eventhandler-filtering-with-topics/feed/</wfw:commentRss>
		</item>
		<item>
		<title>New AbstractViewMediator For Popups Using Swiz 1.0 RC1</title>
		<link>http://www.webappsolution.com/wordpress/2010/08/19/new-abstractviewmediator-for-popups-using-swiz-10-rc1/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/08/19/new-abstractviewmediator-for-popups-using-swiz-10-rc1/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 20:47:34 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[swiz]]></category>

		<category><![CDATA[autowire-view]]></category>

		<category><![CDATA[dependency-injection]]></category>

		<category><![CDATA[inject]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[popups]]></category>

		<category><![CDATA[swiz-1.0]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=828</guid>
		<description><![CDATA[This post builds on my last post regarding the use of the ViewMediator pattern with Swiz. One of the things I hadn&#8217;t tested when I wrote the original AbstractViewMediator (AVM) was popups. Once I started using this base class in a couple projects I realized I had a pretty big hole that I quickly need [...]]]></description>
			<content:encoded><![CDATA[<p>This post builds on my <a href="http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/" target="_blank">last post regarding the use of the ViewMediator pattern with Swiz</a>. One of the things I hadn&#8217;t tested when I wrote the original AbstractViewMediator (AVM) was popups. Once I started using this base class in a couple projects I realized I had a pretty big hole that I quickly need to fix.</p>
<p><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view-popup/AbstractViewMediator.as" target="_blank">Download the new and improved AbstractViewMediator</a>.</p>
<p>Normally, views are added to the display list, but popups are actually added to the <a href="http://livedocs.adobe.com/flex/3/langref/mx/managers/SystemManager.html" target="_blank">SystemManager</a> so they don&#8217;t fire off the <code>flash.events.Event.ADDED_TO_STAGE</code> event that&#8217;s mediated in the <code>setView()</code> method in my AbstractViewMediator and that&#8217;s the core piece of logic behind the entire AbtractViewMediator. <a href="http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/" target="_blank">See the last post for details</a>.</p>
<p>So how would I connect my views to my VMs? The key was to make the AbstractViewMediator actually create the popup via the following method:</p>
<pre class="brush: as3;">
public function createPopupView(
								view:IFlexDisplayObject,
								parent:DisplayObject,
								modal:Boolean = false,
								childList:String = null,
								moduleFactory:IFlexModuleFactory = null
								):IFlexDisplayObject
{
	this.setView(view);

	PopUpManager.addPopUp(view, parent, true); // window:IFlexDisplayObject,parent:DisplayObject,modal:Boolean = false,childList:String = null,moduleFactory:IFlexModuleFactory = null
	PopUpManager.centerPopUp(view);

	return view;
}
</pre>
<p>If you look at the method signature you&#8217;ll see that I pass in a reference to the view we&#8217;re creating and then call the all important <code>public function setView(value:*):void</code> method that&#8217;s usually called by the mediated event <code>flash.events.Event.ADDED_TO_STAGE</code>. This is what creates the connection between a VM and a View. This also brings up a new question &#8212; who calls this method?</p>
<p>In order for the VM to be hooked up to the correct view, we&#8217;ll need to make sure we call the <code>createPopupView(...)</code> method on our concrete VM implementation&#8230;hmm&#8230;so how do we get a hold of that&#8230;ahh yes, the nice guys at Swiz gave us access to it via the list of beans that this instance of Swiz has. Let&#8217;s learn by example.</p>
<p>We&#8217;ll imagine we need to open a popup from <code>MainView</code> after clicking the &#8220;Get Users Button&#8221;. Naturally, our <code>MainViewMediator</code> mediates the button&#8217;s click event and calls this functional method:</p>
<pre class="brush: as3;">
/**
 * Open the create user view.
 */
public function openCreateUserView():void
{
	var view:CreateUserView;
	var vm:CreateUserViewMediator;

	view = new CreateUserView();
	vm = this.getViewMediatorBeanById(&quot;createUserViewMediator&quot;) as CreateUserViewMediator;

	vm.createPopupView(view, this.view, true);
}
</pre>
<p>The key line is where we get a handle to the <code>CreateUserViewMediator</code> via the method <code>getViewMediatorBeanById(...)</code> in the <code>AbstractViewMediator</code>:</p>
<pre class="brush: as3;">
/**
 * Helper method that returns a view mediator managed by Swiz by it's ID.
 *
 * @param	id	The unique ID for the view mediator as defined in the BeanLoader.
 */
public function getViewMediatorBeanById(id:String):AbstractViewMediator
{
	var vm:AbstractViewMediator = this.swiz.beanFactory.getBeanByName(id).source as AbstractViewMediator;

	return vm;
}

/**
 * Helper method that returns a view mediator managed by Swiz by it's ID.
 *
 * @param	clazz	The class type for our view mediator.
 */
public function getViewMediatorBeanByType(clazz:Class):AbstractViewMediator
{
	var vm:AbstractViewMediator = this.swiz.beanFactory.getBeanByType(clazz).source as AbstractViewMediator;

	return vm;
}
</pre>
<p>This method in the AVM also assumes it has a handle to the instance of Swiz that contains the beans. This is done by implementing the <code>ISwizAware</code> interface in the AVM.</p>
<pre class="brush: as3;">
/**
 * Creates a reference to the instance of Swiz this bean is in. This
 * allows us to get a hold of manager beans by using:
 * &lt;code&gt;var vm:MyViewMediator = swiz.beanFactory.getBeanByName(&quot;myViewMediator&quot;).source as MyViewMediator;&lt;/code&gt;
 */
public function set swiz(swiz:ISwiz):void
{
	this._swiz = swiz;
}
public function get swiz():ISwiz
{
	return this._swiz;
}
protected var _swiz:ISwiz;
</pre>
<p>There you have it. All the pieces. If you create popups this way you&#8217;ll get the expected VM to View connection.</p>
<p><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view-popup/AbstractViewMediator.as" target="_blank">Download the new and improved AbstractViewMediator</a>.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=New+AbstractViewMediator+For+Popups+Using+Swiz+1.0+RC1+http://f5bse.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=New+AbstractViewMediator+For+Popups+Using+Swiz+1.0+RC1+http://f5bse.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/08/19/new-abstractviewmediator-for-popups-using-swiz-10-rc1/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz + SourceMate + Metadata Preferences FTW!</title>
		<link>http://www.webappsolution.com/wordpress/2010/04/22/swiz-sourcemate-metadata-preferences-ftw/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/04/22/swiz-sourcemate-metadata-preferences-ftw/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 14:05:28 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flash builder]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[big-papi]]></category>

		<category><![CDATA[dev-tools]]></category>

		<category><![CDATA[development]]></category>

		<category><![CDATA[dispatcher]]></category>

		<category><![CDATA[flex]]></category>

		<category><![CDATA[ide]]></category>

		<category><![CDATA[inject]]></category>

		<category><![CDATA[mediate]]></category>

		<category><![CDATA[metadata]]></category>

		<category><![CDATA[postconstruct]]></category>

		<category><![CDATA[postdestroy]]></category>

		<category><![CDATA[sourcemate]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=800</guid>
		<description><![CDATA[I&#8217;ve obviously been using Swiz quite a bit lately and recently I added SourceMate to my arsenal of Flex tools &#8212; if you don&#8217;t know what SourceMate is, just think of what a good Java IDE can do and envision Flash Builder being able to do the same &#8212; it&#8217;s basically like feeding Flash Builder [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve obviously been using <a href="http://swizframework.org/" target="_blank">Swiz</a> quite a bit lately and recently I added <a href="http://www.elementriver.com/sourcemate" target="_blank">SourceMate</a> to my arsenal of Flex tools &#8212; if you don&#8217;t know what SourceMate is, just think of what a good Java IDE can do and envision Flash Builder being able to do the same &#8212; it&#8217;s basically like feeding Flash Builder steroids or <a href="http://en.wikipedia.org/wiki/David_Ortiz" target="_blank">Big Papi</a> in 2007 with <a href="http://en.wikipedia.org/wiki/Performance-enhancing_drugs" target="_blank">PEDs</a>. Anyways, here&#8217;s a <a href="http://www.elementriver.com/sourcemate/features/" target="_blank">quick list of goodies that it adds to the IDE</a>.</p>
<p>Well my favorite set of enhancements is without a doubt the MetataData Features:</p>
<ul>
<li><a href="http://www.elementriver.com/sourcemate/features/#metaassist" target="_blank">Metadata Content Assist</a></li>
<li><a href="http://www.elementriver.com/sourcemate/features/#metaassist"></a><a href="http://www.elementriver.com/sourcemate/features/#metavalid" target="_blank">Metadata Tag Validation</a></li>
<li><a href="http://www.elementriver.com/sourcemate/features/#metavalid"></a><a href="http://www.elementriver.com/sourcemate/features/#metaimpexp" target="_blank">Import/Export Tag Configuration</a></li>
</ul>
<p>No more trying to remember the exact syntax for custom metadata for frameworks like Swiz&#8230;and even better is the fact that the Swiz doods at UM created a metadata config/preferences XML file for you to import to just start your Swiz project with SourceMate. <a href="http://github.com/swiz/swiz-framework/blob/master/misc/SwizMetadataSourceMateConfig.xml" target="_blank">Grab the file here</a> from the Swiz Github repo and simply add it to your projects&#8217;s SourceMate preferences: Project Properties -&gt; SourceMate -&gt; Metadata -&gt; Import&#8230; browse for the file and boom, you&#8217;r<br />
e good to go!</p>
<div id="attachment_803" class="wp-caption alignnone" style="width: 614px"><img class="size-full wp-image-803  " title="SourceMate Metadata -&gt; Import Swiz Configs" src="http://www.webappsolution.com/wordpress/wp-content/uploads/2010/04/picture-41.png" alt="SourceMate Metadata -&gt; Import Swiz Configs" width="604" height="404" /><p class="wp-caption-text">SourceMate Metadata -&gt; Import Swiz Configs</p></div>
<p>Nice work Swiz doods.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+%2B+SourceMate+%2B+Metadata+Preferences+FTW%21+http://hf6eo.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+%2B+SourceMate+%2B+Metadata+Preferences+FTW%21+http://hf6eo.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/04/22/swiz-sourcemate-metadata-preferences-ftw/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz 1.0 RC1 Removes [Autowire( view="true" )] - Requires New AbstractViewMediator</title>
		<link>http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/#comments</comments>
		<pubDate>Tue, 20 Apr 2010 12:26:19 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[autowire-view]]></category>

		<category><![CDATA[dependency-injection]]></category>

		<category><![CDATA[form-validation]]></category>

		<category><![CDATA[inject]]></category>

		<category><![CDATA[login-view]]></category>

		<category><![CDATA[metadata]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[swiz-1.0]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=784</guid>
		<description><![CDATA[Introduction
With the release of Swiz 1.0 RC1 right around the corner I figured I&#8217;d pull down the latest code from github, do a build, and then migrate my previous examples of Swiz and the Passive View to the latest SWC. I obviously ran into a couple of small changes between Swiz 0.6.4 and 1.0, but [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>With the release of <a href="http://swizframework.org/" target="_blank">Swiz</a> 1.0 RC1 right around the corner I figured I&#8217;d pull down the latest code from <a href="http://github.com/swiz/" target="_blank">github</a>, do a build, and then migrate <a href="http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/" target="_blank">my previous examples of Swiz and the Passive View</a> to the latest SWC. I obviously ran into a couple of small changes between Swiz 0.6.4 and 1.0, but the one that caught me off-gaurd was the removal of metadata that injected views:</p>
<pre class="brush: as3;">
[Autowire( view=&quot;true&quot; )]
</pre>
<p>Of course the first thing I tried was changing the metadata to use the new, preferred metadata tag [Inject]:</p>
<pre class="brush: as3;">
[Inject( view=&quot;true&quot; )]
</pre>
<p>No dice. So I reached out to <a href="http://www.benclinkinbeard.com/" target="_blank">Ben Clinkinbeard</a> and confirmed what I suspected &#8212; the injection of views (or any objects for that matter) that aren&#8217;t defined in the BeanLoader is no longer supported in Swiz 1.0; however, a simple change to my existing, base <code>AbstractViewMediator</code> and any concrete impls (subclasses thereof) fixed that right away &#8212; thanks to Ben for pointing me in the right direction on this one. </p>
<p>Assets:</p>
<ul>
<li><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/AbstractViewMediator.as" target="_blank">AbstractViewMediator.as</a></li>
<li><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/LoginViewMediator.as" target="_blank">LoginViewMediator.as</a></li>
</ul>
<p>Let&#8217;s just take a quick look at what the new <code>AbstractViewMediator</code> looks like:</p>
<p><strong>AbstractViewMediator</strong></p>
<p><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/AbstractViewMediator.as" target="_blank">AbstractViewMediator.as</a></p>
<pre class="brush: as3;">
/**
* Web App Solution Confidential Information
* Copyright 2010, Web App Solution, Inc.
*
* @date April, 15, 2010
*/
package com.webappsolution.mediator
{
	import com.webappsolution.logging.LocalConnectionLog;
	import com.webappsolution.model.IAppModel;

	import flash.events.Event;
	import flash.events.IEventDispatcher;

	import mx.core.UIComponent;
	import mx.events.FlexEvent;
	import mx.logging.ILogger;

	/**
	 * The base class for all view mediators. It's most useful function is to
	 * provide the metadata and setter method to inject the corresponding view into
	 * the mediator.
	 *
	 * &lt;p&gt;
	 * In addition, it allows concrete View Mediators to add view event handlers
	 * and data bindings to children of the corresponding View with confidence by
	 * by determining if the view is &quot;alive&quot; (aka has been instantiated and added to
	 * the stage -- creationComplete event fired) or if it needs to listen for it's
	 * creation complete event before performing actions on it. See the
	 * &lt;code&gt;public function setView( value:* ):void&lt;/code&gt; method for more
	 * details on this.
	 * &lt;/p&gt;
	 */
	public class AbstractViewMediator
	{
		/**
		 * Logger.
		 */
		private static const logger:ILogger = LocalConnectionLog.getLogger(AbstractViewMediator);

		/**
		 * A flag indicating if the correpsonding view's creation complete has fired.
		 */
		public var isViewCreationComplete:Boolean = false;

		/**
		 * The view class we're injecting into the view mediator.
		 */
		protected var viewType:Class;

		/**
		 * The view that corresponds to this view mediator.
		 */
		protected var _view:UIComponent;

		/**
		 * Constructor.
		 */
		public function AbstractViewMediator(viewType:Class)
		{
			super();
			logger.debug(&quot;Constructor&quot;);

			this.viewType = viewType;
		}

		/**
		 * Allows this class to dispatch events. The event dispatcher is
		 * injected by Swiz due to the [Dispatcher] metadata and the class
		 * memeber's type of IEventDispatcher.
		 */
		[Dispatcher]
		public var dispatcher:IEventDispatcher;

		/**
		 * Instruct Swiz to Inject the ApplicationModel by type.
		 */
		[Inject]
		public function set appModel(value:IAppModel):void
		{
			logger.debug(&quot;AUTOWIRE :: appModel = &quot; + value);

			this._appModel = value;
		}
		public function get appModel():IAppModel
		{
			return this._appModel;
		}
		private var _appModel:IAppModel;

		/**
		 * Listen for views added to the stage and determine if it's the corresponding
		 * View for this View Mediator. This check is done by looking at the view added
		 * to the stage and do a simple compare on the &lt;code&gt;viewType:Class&lt;/code&gt; class
		 * member that we set in concrete View Medators via their constructors.
		 *
		 * &lt;p&gt;
		 * Also determine if the View has fired its creation complete event so developers
		 * can perform actions on the view from the View Mediator without hitting null pointers
		 * for uninstantiated objects in the View. If the creation complete has not fired, then
		 * listen for it.
		 * &lt;/p&gt;
		 */
		[Mediate( &quot;flash.events.Event.ADDED_TO_STAGE&quot;, properties=&quot;target&quot;, useCapture=&quot;true&quot; )]
		public function setView(value:*):void
		{
			if(value is viewType)
			{
				logger.debug(&quot;AUTOWIRE :: view = &quot; + value);
				this._view = value;

				// determine if the view has been initialized...
				// NO...listen for it;s creation complete event
				if(this._view.initialized == false)
				{
					this._view.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
				}
					// YES...call the init() method to kick off the instation of the view mediator
				else
				{
					this.isViewCreationComplete = true;
					this.init();
				}

				// don't get in GC's way if the view is removed
				this._view.addEventListener(Event.REMOVED_FROM_STAGE, cleanup);
			}
			else
			{
//				logger.warn(&quot;Don't inject the view &quot; + value);
			}
		}

		/**
		 * The &lt;code&gt;init()&lt;/code&gt; method is only called when the ViewMediator's corresponding
		 * View's creationComplete has been fired; this allows developers to add event listens,
		 * data bindings, and any other view functions in confidence (without worry about accessing
		 * children of the view that are null and cause runtime errors.)
		 *
		 * &lt;p&gt;
		 * Developers can override this to perform additional initializaitons in their ViewMediator,
		 * but must call &lt;code&gt;super.init()&lt;/code&gt; in order for the aforementioned to function
		 * correctly.
		 * &lt;/p&gt;
		 *
		 * &lt;p&gt;
		 * Does not have to be overriden. Simple here for convenience and as a marker method
		 * &lt;/p&gt;
		 */
		protected function init():void
		{
			logger.debug(&quot;init&quot;);
			this.setViewListeners();
			this.setViewDataBindings();
		}

		/**
		 * Set the listeners for the UI components on the stage for the ViewMediator's corresponding View.
		 *
		 * &lt;p&gt;
		 * Does not have to be overriden. Simple here for convenience and as a marker method
		 * &lt;/p&gt;
		 */
		protected function setViewListeners():void
		{
			logger.debug(&quot;setViewListeners&quot;);
			// OVERRIDDEN
		}

		/**
		 * Set the data bindings for the UI components on the stage for the ViewMediator's corresponding View.
		 *
		 * &lt;p&gt;
		 * Does not have to be overriden. Simple here for convenience and as a marker method
		 * &lt;/p&gt;
		 */
		protected function setViewDataBindings():void
		{
			logger.debug(&quot;setViewDataBindings&quot;);
			// OVERRIDDEN
		}		

		/**
		 * Listen for the creation complete of the View for this ViewMediator.
		 */
		protected function onCreationComplete( event:FlexEvent ):void
		{
			logger.debug(&quot;onCreationComplete&quot;);

			this.isViewCreationComplete = true;
			this._view.removeEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
			this.init();
		}

		/**
		 * Remove any listeners we've created.
		 *
		 * &lt;p&gt;
		 * Developers should override this method to remove any custom listners
		 * created in the concrete ViewMediator. Developers must call
		 * &lt;code&gt;super.cleanup()&lt;/code&gt; in order for this to function correctly.
		 * &lt;/p&gt;
		 */
		protected function cleanup( event:Event ):void
		{
			logger.debug(&quot;cleanup&quot;);
			this._view.removeEventListener(Event.REMOVED_FROM_STAGE, cleanup);
		}
	}
}
</pre>
<p>The key change here is the changes to the <code>public function setView(value:*):void</code> method. Notice how it&#8217;s mediating the added to stage event &#8212; this event mediation checks to see if the View that was added to the stage is in fact the corresponding View for this View Mediator. Now you have to ask, but where is the viewType set for this check? And the answer is in each concrete impl&#8217;s constructor of the View Mediator. Here&#8217;s a quick example in a LoginViewMediator:</p>
<p><strong>LoginViewMediator</strong></p>
<p><a href="http://www.webappsolution.com/flex/blog/examples/swiz-rc1-passive-view/LoginViewMediator.as" target="_blank">LoginViewMediator.as</a></p>
<pre class="brush: as3;">
/**
 * Web App Solution Confidential Information
 * Copyright 2010, Web App Solution, Inc.
 *
 * @date April, 15, 2010
 */
package com.webappsolution.mediator
{
	import com.webappsolution.event.ApplicationEvent;
	import com.webappsolution.logging.LocalConnectionLog;
	import com.webappsolution.view.LoginView;

	import flash.events.Event;
	import flash.events.MouseEvent;

	import mx.controls.TextInput;
	import mx.events.ValidationResultEvent;
	import mx.logging.ILogger;
	import mx.validators.EmailValidator;
	import mx.validators.StringValidator;
	import mx.validators.Validator;

	/**
	 * Handles all events, data manipulation, data bindings, and whatever else it's
	 * corresponding View can dish out.
	 */
	public class LoginViewMediator extends AbstractViewMediator
	{
		/**
		 * Logger.
		 */
		private static const logger:ILogger = LocalConnectionLog.getLogger(LoginViewMediator);

		/**
		 * Field validator for the user name form field.
		 */
		protected var userNameValidator:EmailValidator;

		/**
		 * Field validator for the password form field.
		 */
		protected var passwordValidator:StringValidator;

		/**
		 * Constructor.
		 */
		public function LoginViewMediator(viewType:Class=null)
		{
			super(LoginView);
			logger.debug(&quot;Constructor&quot;);
		}

		/**
		 * Since the AbstractViewMediator sets the view via Autowiring in Swiz,
		 * we need to create a local getter to access the underlying, expected view
		 * class type.
		 */
		public function get view():LoginView
		{
			return this._view as LoginView;
		}

		/**
		 * The &lt;code&gt;init()&lt;/code&gt; method is fired off automatically by the
		 * AbstractViewMediator when the creation complete event fires for the
		 * corresponding ViewMediator's view. This allows us to listen for events
		 * and set data bindings on the view with the confidence that our view
		 * and all of it's child views have been created and live on the stage.
		 */
		override protected function init():void
		{
			super.init();
			logger.debug(&quot;init&quot;);

			// create the form validators for the login panel
			this.createFormValidators();

			// disable the submit btn to start
			this.view.submitBtn.enabled = false;

			// make the submit btn the default btn so hitting enters submits the form
			this.view.loginForm.defaultButton = this.view.submitBtn;

			// set the focus to the username field
			this.view.userNameTextInput.setFocus();
		}

		/**
		 * Create listeners for all of the view's children that dispatch events
		 * that we want to handle in this mediator.
		 */
		override protected function setViewListeners():void
		{
			super.setViewListeners();
			logger.debug(&quot;setViewListeners&quot;);

			// handle user input on the form fields for instant form validation feedback
			this.view.userNameTextInput.addEventListener(Event.CHANGE, inputChgHandler);
			this.view.passwordTextInput.addEventListener(Event.CHANGE, inputChgHandler);

			// handle the click of the submit button
			this.view.submitBtn.addEventListener(MouseEvent.CLICK, submitBtnClickHandler);
		}

		/**
		 * Handles the click event from the submit button.
		 * Grabs the username and password from the respeective text
		 * input fields and populates a LoginDTO, then dispatches the
		 * LoginEvent to the Cairngorm framework.
		 */
		protected function submitBtnClickHandler(evt:MouseEvent):void
		{
			logger.debug(&quot;submitBtnClickHandler&quot;);

			var userName:String;
			var password:String;

			userName = this.view.userNameTextInput.text;
			password = this.view.passwordTextInput.text;

			this.login(userName, password);
		}

		/**
		 * The functional login method that dispatches the login event with the
		 * username and password.
		 *
		 * @param userName
		 * @param password
		 */
		protected function login(userName:String, password:String):void
		{
			var appEvt:ApplicationEvent;

			appEvt = new ApplicationEvent(ApplicationEvent.SERVICE_LOGIN);
			appEvt.username = userName;
			appEvt.password = password;
			this.dispatcher.dispatchEvent(appEvt);
		}

		/**
		 * Create the form field validators for the login fields.
		 */
		protected function createFormValidators():void
		{
			logger.debug(&quot;createFormValidators&quot;);

			// create the user name validator
			this.userNameValidator = new EmailValidator();
			this.userNameValidator.requiredFieldError = &quot;Please enter a valid email address.&quot;;
			this.userNameValidator.property = &quot;text&quot;;

			// create the password validator
			this.passwordValidator = new StringValidator();
			this.passwordValidator.required = true;
			this.passwordValidator.requiredFieldError = &quot;Please enter a password.&quot;;
			this.passwordValidator.minLength = 4;
			this.passwordValidator.property = &quot;text&quot;;
		}

		/**
		 * Handles text input changes to the username and password and validate them.
		 * Only enable the submit button if both the username and password fields
		 * are valid.
		 *
		 * @param evt    Change event from the targeted input field.
		 */
		protected function inputChgHandler(evt:Event):void
		{
			this.view.submitBtn.enabled =
				this.isTextInputFieldValid(this.view.userNameTextInput, this.userNameValidator) &amp;&amp;
				this.isTextInputFieldValid(this.view.passwordTextInput, this.passwordValidator);
		}

		/**
		 * Determines if the username text input is valid.
		 * @return Boolean
		 */
		protected function isTextInputFieldValid(textInput:TextInput, validator:Validator):Boolean
		{
			textInput.errorString = &quot;&quot;;

			var resultEvent:ValidationResultEvent = validator.validate(textInput.text);
			if (resultEvent.type != ValidationResultEvent.VALID)
			{
				textInput.errorString = resultEvent.message;
			}
			return (resultEvent.type == ValidationResultEvent.VALID);
		}

		/**
		 * Remove any listeners we've created.
		 */
		override protected function cleanup( event:Event ):void
		{
			super.cleanup(event);
			logger.debug(&quot;cleanup&quot;);

			this.view.userNameTextInput.removeEventListener(Event.CHANGE, inputChgHandler);
			this.view.passwordTextInput.removeEventListener(Event.CHANGE, inputChgHandler);
			this.view.submitBtn.removeEventListener(MouseEvent.CLICK, submitBtnClickHandler);
		}
	}
}
</pre>
<p>There are two things to note here:</p>
<p><strong>1) The setting of the view type via the Constructor</strong></p>
<pre class="brush: as3;">
public function LoginViewMediator(viewType:Class=null)
{
super(LoginView);
logger.debug(&quot;Constructor&quot;);
}
</pre>
<p><strong>2) The use of a getter method for strong typing of the View in the View Mediator</strong></p>
<pre class="brush: as3;">
public function get view():LoginView
{
return this._view as LoginView;
}
</pre>
<p>Now armed with a new version of the <code>AbstractViewMediator</code> you can go back to using Swiz with your View Mediators without any issues.</p>
<p><strong>NOTE</strong>: In order for this to work you must pull down the latest code from <a href="http://github.com/swiz/" target="_blank">github</a> and compile the SWC with the ant build.xml file provided with the project. Do not attempt to use this with the currently released Swiz Beta 1 SWC.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+1.0+RC1+Removes+%5BAutowire%28+view%3D%22true%22+%29%5D+-+Requires+New+AbstractViewMediator+http://ncz7k.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+1.0+RC1+Removes+%5BAutowire%28+view%3D%22true%22+%29%5D+-+Requires+New+AbstractViewMediator+http://ncz7k.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/04/20/swiz-10-rc1-removes-autowire-viewtrue-requires-new-abstractviewmediator/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz Passive View Example :: Part 2</title>
		<link>http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 15:22:36 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[design-pattern]]></category>

		<category><![CDATA[form-validation]]></category>

		<category><![CDATA[login-view]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[service-locator]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=727</guid>
		<description><![CDATA[Introduction
After implementing Part 1 of the Swiz + Passive View (PV) Example, I immediately decided that one thing I missed from the original Spring ActionScript (SAS) version was the ability to create services in an XML file that&#8217;s loaded at runtime, thus allowing you to take your app from one environment to another and simply [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>After implementing <a href="http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/" target="_blank">Part 1 of the Swiz + Passive View (PV) Example</a>, I immediately decided that one thing I missed from the <a href="http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/" target="_blank">original Spring ActionScript (SAS) version</a> was the ability to create services in an XML file that&#8217;s loaded at runtime, thus allowing you to take your app from one environment to another and simply change the XML as opposed to recompiling. Some devs don&#8217;t seem to care about this, but I find it quite useful and so do many of my clients so I created a simple <code>DynamicServiceLocator</code> (SL) class and &#8220;injected&#8221; it into my Example.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Create a Dynamic Service Locator that Instantiates Services from an External XML File at Runtime</strong></p>
<p><strong>Assets</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-1/EmpMgmtConsoleSwizPassiveView.html" target="_blank">Demo Application</a></li>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-1/srcview/" target="_blank">View Source</a></li>
</ul>
<p><strong>Acronyms</strong></p>
<ul>
<li>PV = PassiveView</li>
<li>SAS = Spring ActionScript</li>
<li>SL = Service Locator</li>
<li>VM = View Mediator</li>
<li>CG = Cairngorm</li>
<li>IoC = Inversion of Control</li>
<li>DTO = Data Transfer Object</li>
</ul>
<p><strong>Caveats</strong></p>
<p>Please read the previous posts in this series to get up to speed:</p>
<ol>
<li><a href="http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/" target="_blank">Part 1 of the Swiz + Passive View (PV) Example</a></li>
</ol>
<p>I won&#8217;t go into the details of what Swiz is and how it works as I&#8217;d like to let the code speak for itself and you can just hit up the Swiz homepage and view their simple examples; that said, I&#8217;ll point out several things I really like about Swiz.</p>
<p>I am using Swiz 0.6.4, as I found issues with the <a href="http://swizframework.org/2009/12/swiz-1-0-0-alpha-released/" target="_blank">1.0.0 alpha release</a> (that I&#8217;m going to bring up with <a href="http://www.benclinkinbeard.com/" target="_blank">Ben Clinkenbeard</a>).</p>
<p><strong>Getting Started</strong></p>
<p>The idea is simple:</p>
<ol>
<li>Create an XML file that defines all of the services leveraged in the app.</li>
<li>Add the <code>DynamicServiceLocator</code> to the <code>BeanLoader</code> (Beans.mxml) and give it the URL to load the services XML file.</li>
<li>Listen to the <code>DynamicServiceLocator</code>&#8217;s complete event, indicating that the services are loaded and parsed, and start the app up.</li>
<li>Inject the SL into the Delegates as opposed to injecting the services directly (that were previously defined and hardcoded in the <code>BeanLoader</code> from <a href="http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/" target="_blank">Part 1</a>).</li>
<li>In the Delegate, request a service from the <code>DynamicServiceLocator</code> via an ID that was set in the service&#8217;s definition in the XML file.</li>
<li>Use the service.</li>
</ol>
<p>Let’s take it piece by piece…</p>
<p><strong>Step 1: Create Services XML File</strong></p>
<p>Let&#8217;s start by creating an XML file called services.xml and putting it in src/assets/service-locator/. Next, let&#8217;s add some services &#8212; truth be told, I took the format for the XML that defines a service directly from the idea behind the application context files used in SAS and then created my own Object Factory&#8230;it&#8217;s very simple mind you b/c I didn&#8217;t need a huge object factory taking up a ton of memory when the only objects it would ever create were 8 different services.</p>
<pre class="brush: xml;">
&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot;?&amp;gt;
&amp;lt;objects&amp;gt;

&amp;lt;!-- =================================================================== --&amp;gt;
&amp;lt;!-- SERVICE LOCATOR --&amp;gt;
&amp;lt;!-- =================================================================== --&amp;gt;

&amp;lt;!-- =================================================================== --&amp;gt;
&amp;lt;!-- This application context defines multiple test configurations, it
can be expanded to include a deployment configuration as well,
please see comments below.

1. Local Testing: XML Services
2. Dev Server Testing: XML Services
3. Deployment: XML Services
--&amp;gt;
&amp;lt;!-- =================================================================== --&amp;gt;

&amp;lt;!-- =================================================================== --&amp;gt;
&amp;lt;!-- 1. LOCAL TESTING: XML Services --&amp;gt;
&amp;lt;!-- =================================================================== --&amp;gt;

	&amp;lt;object id=&amp;quot;loginService&amp;quot; class=&amp;quot;mx.rpc.http.mxml.HTTPService&amp;quot;&amp;gt;
		&amp;lt;property name=&amp;quot;url&amp;quot; value=&amp;quot;assets/xml/login.xml&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;resultFormat&amp;quot; value=&amp;quot;e4x&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;method&amp;quot; value=&amp;quot;GET&amp;quot; /&amp;gt;
	&amp;lt;/object&amp;gt;

	&amp;lt;object id=&amp;quot;employeeService&amp;quot; class=&amp;quot;mx.rpc.http.mxml.HTTPService&amp;quot;&amp;gt;
		&amp;lt;property name=&amp;quot;url&amp;quot; value=&amp;quot;assets/xml/employee_list.xml&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;resultFormat&amp;quot; value=&amp;quot;e4x&amp;quot; /&amp;gt;
		&amp;lt;property name=&amp;quot;method&amp;quot; value=&amp;quot;GET&amp;quot; /&amp;gt;
	&amp;lt;/object&amp;gt;

&amp;lt;/objects&amp;gt;
</pre>
<p>The idea is to create a list of services as object nodes. Start by giving each <code>&lt;object&gt;</code> node a unique <code>id</code> attribute, as this is the key we&#8217;ll use to request the service later. The following line defines the loginService:</p>
<pre class="brush: xml;">
&amp;lt;object id=&amp;quot;loginService&amp;quot; class=&amp;quot;mx.rpc.http.mxml.HTTPService&amp;quot;&amp;gt;
</pre>
<p>Next, define the concrete Flex service type in the <code>class</code> attr  &#8212; right now the service class must be one of the following types:</p>
<ul>
<li><code>mx.rpc.http.mxml.HTTPService</code></li>
<li><code>mx.rpc.http.HTTPService</code></li>
<li><code>mx.rpc.remoting.mxml.RemoteObject</code></li>
<li><code>mx.rpc.remoting.RemoteObject</code></li>
<li><code>mx.rpc.soap.mxml.WebService</code></li>
<li><code>mx.rpc.soap.WebService</code></li>
</ul>
<p>Finally, add any additional properties you want to define for the service as <code>&lt;property&gt;</code> nodes with the <code>name</code> and <code>value</code> attrs matching properties that are available for the service type. The following line adds the <code>url</code> property for the <code>HTTPService</code>:</p>
<pre class="brush: xml;">
&amp;lt;property name=&amp;quot;url&amp;quot; value=&amp;quot;assets/xml/login.xml&amp;quot; /&amp;gt;
</pre>
<p><strong>Step 2: Add DynamicServiceLocator to the BeanLoader</strong></p>
<p>We&#8217;ll add the SL to the <code>BeanLoader</code> just like we did for all the other objects we want managed by the IoC Container, except we&#8217;ll also provide her with the URL to our services.xml file that we just created. When the <code>url</code> property is set on the SL, it will automatically load the services, parse the XML, instantiate a service for each <code>&lt;object&gt;</code> node it finds that matches one of the aforementioned service classes, and then adds that service to it&#8217;s hash or <code>Dictionary</code> object&#8217;s list of services via the <code>id</code> as it&#8217;s key.</p>
<pre class="brush: as3;">
&amp;lt;service:DynamicServiceLocator id=&amp;quot;serviceLocator&amp;quot; eventDispatcher=&amp;quot;{this.dispatcher}&amp;quot; url=&amp;quot;assets/service-locator/services.xml&amp;quot; /&amp;gt;
</pre>
<p>The other thing to make note of is that we&#8217;re again passing a reference to the BeanLoader&#8217;s dispatcher so the SL can broadcast events to other objects in the Swiz IoC Container.</p>
<p><strong>Step 3: Listen to the SL&#8217;s Services Load Complete Event</strong></p>
<p>Since this is more of an application level event, we&#8217;ll make the <code>ApplicationController</code> object handle this event:</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;serviceLocatorServicesLoadComplete&amp;quot; )]
public function onServiceLocatorLoadComplete():void
{
	logger.debug(&amp;quot;onServiceLocatorLoadComplete&amp;quot;);

	this.eventDispatcher.dispatchEvent(new DynamicEvent(&amp;quot;showMainView&amp;quot;));
}
</pre>
<p>Which then in turn broadcasts a &#8220;showMainView&#8221; event that&#8217;s handled by the <code>ApplicationViewMediator</code> and ultimately removes a simple preloader (which is there in case the SL should take any significant amount of time to load and parse &#8212; unlikely here, but useful in the future) and adds the <code>MainView</code> to the stage.</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;showMainView&amp;quot; )]
public function showMainView():void
{
	logger.debug(&amp;quot;showMainView&amp;quot;);

	this.view.removeChild(this.view.progressBar);
	this.view.addChild(new MainView());
}
</pre>
<p>Now this may seem like overkill for this extremely simple example, as I could have just listened to the &#8220;serviceLocatorServicesLoadComplete&#8221; in the <code>ApplicationViewMediator</code>, but I wanted to proxy the event through the <code>ApplicationController</code> in case more needed to be done&#8230;What if we wanted to update a model level var to indicate that the SL was complete? What if we wanted to tell other objects that the SL was complete?&#8230;we wouldn&#8217;t want to do that from the <code>ApplicationViewMediator</code> as it&#8217;s sole purpose is to lend a hand to the <code>MainView</code> UI component and not to orchestrate application level processing, work, etc. Again, overkill in this example, but I wanted to put it in here as an example of what you might want to do in a much larger application.</p>
<p><strong>Step 4: Inject the SL into the Delegates</strong></p>
<p>Next we&#8217;ll want to inject the SL into the Delegates as opposed to injecting the hardcoded services defined in the <code>BeanLoader</code>. First, let&#8217;s declare the new <code>serviceLocator</code> property for the Delegate:</p>
<pre class="brush: as3;">
[Autowire(bean=&amp;quot;serviceLocator&amp;quot;)]
public var serviceLocator:DynamicServiceLocator;
</pre>
<p>Next, let&#8217;s remove the <code>service</code> var&#8217;s declaration and create a simple getter method for it instead:</p>
<pre class="brush: as3;">
public function get service():HTTPService
{
	return this.serviceLocator.getMXMLHTTPService(&amp;quot;loginService&amp;quot;);
}
</pre>
<p><strong>Step 5: Request Service From SL</strong></p>
<p>This allows us to leave the actual use of the <code>service</code> property untouched in our service method calls - this code hasn&#8217;t changed from Part 1, but I&#8217;m showing it for clarity. We&#8217;ll look at the Login Delegate for example:</p>
<pre class="brush: as3;">
public function login(dto:LoginDTO):AsyncToken
{
	logger.debug(&amp;quot;login&amp;quot;);

	return this.service.send();
}
</pre>
<p><strong>Wrapping Up</strong></p>
<p>The only other thing that I failed to mention that&#8217;s different from Part 1 is the use of a simple <code>ProgressBar</code> component in the <code>Application</code> root to provide the user with some additional feedback while the SL is loading and parsing. If you look at the main application file <code>EmpMgmtConsoleSwizPassiveView</code> you&#8217;ll notice that the <code>MainView</code> is now replaced by the <code>ProgressBar</code> component &#8212; once the SL is complete the <code>ProgressBar</code> is removed from the stage and the <code>MainView</code> is added (as mentioned in Step 3).</p>
<p>Finally, to test out the dynamic SL, open up the services.xml file in the example source code and comment out the first set of services that point to local, project-level XML files and ucomment the services that point to the WASI server. See, no recompiling.</p>
<p>And that about does it. Any questions?</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+2+http://ze46x.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+2+http://ze46x.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/01/07/swiz-passive-view-example-part-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Swiz Passive View Example :: Part 1</title>
		<link>http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/</link>
		<comments>http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/#comments</comments>
		<pubDate>Wed, 06 Jan 2010 18:46:26 +0000</pubDate>
		<dc:creator>brianr</dc:creator>
		
		<category><![CDATA[flex]]></category>

		<category><![CDATA[swiz]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[design-pattern]]></category>

		<category><![CDATA[form-validation]]></category>

		<category><![CDATA[login-view]]></category>

		<category><![CDATA[passive-view]]></category>

		<category><![CDATA[view-mediator]]></category>

		<guid isPermaLink="false">http://www.webappsolution.com/wordpress/?p=699</guid>
		<description><![CDATA[Introduction
If you followed my previous posts on the Employment Management Console application leveraging Spring ActionScript + Cairngorm, then you&#8217;ll be familiar with this small example as I simply ported it over from SAS + CG to Swiz using the Passive View (PV) design pattern.
Tutorial Goal: Create an Employee Management Console using Swiz and the Passive [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction</strong></p>
<p>If you followed my <a href="http://www.webappsolution.com/wordpress/2009/06/26/flex-cairngorm-spring-actionscript-part-5-announcement/" target="_blank">previous posts on the Employment Management Console application leveraging Spring ActionScript + Cairngorm</a>, then you&#8217;ll be familiar with this small example as I simply ported it over from SAS + CG to <a href="http://swizframework.org/" target="_blank">Swiz</a> using the <a href="http://blogs.adobe.com/paulw/archives/2007/11/presentation_pa_6.html">Passive View (PV) design pattern</a>.</p>
<p><strong><span style="color: #008000;">Tutorial Goal</span></strong><strong>: Create an Employee Management Console using Swiz and the Passive View Design Pattern<br />
</strong></p>
<p><strong>Assets</strong></p>
<ul>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-0/EmpMgmtConsoleSwizPassiveView.html" target="_blank">Demo Application</a></li>
<li><a href="http://www.webappsolution.com/flex/blog/examples/emp-mgmt-console-swiz-passive-view-0/srcview/" target="_blank">View Source</a></li>
</ul>
<p><strong>Acronyms</strong></p>
<ul>
<li>PV = PassiveView</li>
<li>VM = ViewMediator</li>
<li>CG = Cairngorm</li>
<li>IoC = Inversion of Control</li>
<li>DTO = Data Transfer Object</li>
</ul>
<p><strong>Caveats</strong></p>
<p>I won&#8217;t go into the details of what Swiz is and how it works as I&#8217;d like to let the code speak for itself and you can just hit up the Swiz homepage and view their simple examples; that said, I&#8217;ll point out several things I really like about Swiz.</p>
<p>I am using Swiz 0.6.4, as I found issues with the <a href="http://swizframework.org/2009/12/swiz-1-0-0-alpha-released/" target="_blank">1.0.0 alpha release</a> (that I&#8217;m going to bring up with <a href="http://www.benclinkinbeard.com/" target="_blank">Ben Clinkenbeard</a>).</p>
<p>As an additional side note, I chose the PV because I was always a fan of code-behind &#8212; I like separation of concerns so much that I actually detest looking at MXML with ActionScript in it &#8212; what a mess!..that and the fact that MXML is declarative and should just perform basic UI layout and not presentation logic. What I love about the PV is that it relies on composition as opposed to inheritance (ie the biggest issue I have with code-behind).</p>
<p>Finally, there are other examples of the PV + Swiz out there, like <a href="http://www.benclinkinbeard.com/2009/10/swiz-example-application-with-passive-view-pattern/" target="_blank">Ben Clinkenbeard&#8217;s example</a>, but I went ahead and created an <code>AbstractViewMediator</code> that takes care of some race conditions when working with Views in a ViewMediator, like setting event handlers and data bindings. And I did some other things that I didn&#8217;t see in others that I&#8217;ll point out.</p>
<p><strong>Swiz is Noninvasive</strong></p>
<p>Swiz is a noninvasive framework that allows you to provide well organized structure and architecture to your app without writing a ton of boilerplate code that can be overly verbose and time consuming. Remember CG and how you were forced to do the following for service calls:</p>
<ol>
<li>Create an <code>Event</code> that extends the <code>CairngormEvent</code>.</li>
<li>Create a <code>Command</code> to act as a responder for your service call.</li>
<li>Create a corresponding <code>Delegate</code> that actually makes the service call and transforms your data to client-side types before returning it to the <code>Command</code>.</li>
<li>Don&#8217;t forget to map your Custom CG Event to your Command in the <code>FrontController</code>.</li>
<li>Wash, rinse, repeat&#8230;and repeat&#8230;and repeat&#8230;and&#8230;mehhh</li>
</ol>
<p>With Swiz, you can (and I emphasize can b/c you can still do it the old school way too) just broadcast a <a href="http://www.adobe.com/livedocs/flex/3/langref/mx/events/DynamicEvent.html" target="_blank"><code>DynamicEvent</code></a> from any object in the <a href="http://martinfowler.com/articles/injection.html" target="_blank">IoC Container</a> (those objects that are defined in the Swiz <code>BeanLoader</code> &#8212; in my example, it&#8217;s in the class Beans.mxml) and then add some metadata to another object in the Container to &#8220;Mediate&#8221; that event.</p>
<p>Here&#8217;s an example &#8212; so in my <strong>LoginViewMediator</strong> I want to broadcast a &#8220;login&#8221; type event and pass the username and password along with it and I want my <code>LoginController</code> to handle this event:</p>
<pre class="brush: as3;">
private function submitBtnClickHandler(evt:MouseEvent):void
{
logger.debug(&amp;quot;submitBtnClickHandler&amp;quot;);

var dto:LoginDTO;

// create a login dto to contain the required fields for login
dto = new LoginDTO();
dto.userName = this.view.userNameTextInput.text;
dto.password = this.view.passwordTextInput.text;

var dynEvt:DynamicEvent = new DynamicEvent(&amp;quot;login&amp;quot;);
dynEvt.dto = dto;
this.eventDispatcher.dispatchEvent(dynEvt);
}
</pre>
<p>And now we handle this event in the <strong>LoginController</strong> like so:</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;login&amp;quot;, properties=&amp;quot;dto&amp;quot; )]
public function login( dto:LoginDTO ):void
{
logger.debug(&amp;quot;login&amp;quot;);

// TODO - make service call -- see in example src code
}
</pre>
<p>So let&#8217;s dig a bit deeper here and note all the cool stuff that&#8217;s going on and why I&#8217;m psyched about Swiz + PV:</p>
<p><strong>No Custom Events (If You Don&#8217;t Want To)</strong></p>
<p>Notice that I didn&#8217;t have to create a custom Event &#8212; less code &#8212; YES! Now, you can by all means create a custom event and Swiz will type check the event object and the event type to make sure they exist &#8212; check it out in the <a href="http://swizframework.org/docs/event-handling/#typed_event" target="_blank">Swiz Docs for Event Handling</a> &#8212; or you can save yourself some extra code and do what I did. While I&#8217;m usually a stickler for strongly typed objects, sometimes you have to ask yourself it it&#8217;s not just overkill for something as simple as this&#8230;personally preference I suppose, but less code without sacrificing organization and good practices wins that battle in my head.</p>
<p><strong>Event Mediation</strong></p>
<p>Swiz automatically handles the event and passes the meat of the event (the <code>LoginDTO</code> that I packages in my <code>DynamicEvent</code>) for me&#8230;uhm, yeah&#8230;that&#8217;s frigging cool! And you can pass multiple args as well. Again, see Swiz Docs. <strong>NOTE</strong>: One thing to remember about event mediation is that the handler method must be marked public &#8212; I&#8217;m used to making event handlers protected (and sometimes even private), but this won&#8217;t allow the Swiz event mediation to work it&#8217;s magic so <strong>make sure event handler methods are marked as public</strong>.</p>
<p><strong>No Logic in MXML</strong></p>
<p>My <code>LoginViewMediator</code> grabs the username and password from it&#8217;s corresponding <code>LoginView</code> and creates the event and DTO. The actual <code>LoginView</code> is just MXML&#8230;nuff said.</p>
<p><strong>Event Dispatching and Handling Thereof in IoC Container Objects</strong></p>
<p>Notice that the <code>LoginViewMediator</code> broadcasts the event from a class member variable called &#8220;eventDispatcher&#8221;. <strong>This next part is important</strong>: in order for Swiz to <em>Mediate</em> events, the events need to go through the central event bus using <code>Swiz.dispatch(&lt;eventType&gt;)</code> or by using the event dispatcher in the <code>BeanLoader</code> &#8212; I have chosen the latter. Why?&#8230;I have 2 reasons:</p>
<ol>
<li>I don&#8217;t like having a reference of Swiz in my classes &#8212; it&#8217;s just unnecessary and makes my application that much more coupled to the framework, something Swiz tries to get developers away from to begin with.</li>
<li>The Swiz.as class is a singleton and singletons are bad&#8230;this is too long a topic to get into, but my main reason has to do with the use of Modules in large Flex apps and while this example doesn&#8217;t require modules, I&#8217;d still rather just stay the hell away from singletons.</li>
</ol>
<p>I shove a reference of the BeanLoader&#8217;s eventDispatched into my IoC Container managed objects like this:</p>
<pre class="brush: as3;">
&amp;lt;controller:LoginController id=&amp;quot;loginController&amp;quot; eventDispatcher=&amp;quot;{this.dispatcher}&amp;quot; /&amp;gt;
&amp;lt;mediator:LoginViewMediator id=&amp;quot;loginViewMediator&amp;quot; eventDispatcher=&amp;quot;{this.dispatcher}&amp;quot; /&amp;gt;
</pre>
<p>Note that they both don&#8217;t need it in order for the controller to hear events from the view mediator &#8212; just the object broadcasting the event needs to have a reference to it, but I pushed it into the controller as well as since I&#8217;m broadcasting other events from it that I&#8217;d like other managed objects to listen to via mediation.</p>
<p><strong>AbstractViewMediator</strong></p>
<p>Since all of my views need a reference to their corresponding view, I decided to create a super class for all the mediators called <code>AbstractViewMediator</code>. This bad boy does several things starting with the injection of the view:</p>
<pre class="brush: as3;">
[Autowire( view=&amp;quot;true&amp;quot; )]
public function set view( value:* ):void
{
logger.debug(&amp;quot;AUTOWIRE :: view = &amp;quot; + value);
this._view = value;

// determine if the view has been initialized...
// NO...listen for it;s creation complete event
if(this._view.initialized == false)
{
this._view.addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
}
// YES...call the init() method to kick off the instation of the view mediator
else
{
this.init();
}

// don't get in GC's way if the view is removed
this._view.addEventListener(Event.REMOVED_FROM_STAGE, cleanup);
}
</pre>
<p>Again, there&#8217;s a couple things to note about this method:</p>
<ol>
<li>The argument for the method is untyped, so how does the concrete <code>ViewMediator</code> (VM) know how to inject the correct view? And then what about code-hinting for the view in the VM? Well, if you look at an actual implementation of a VM, like the <code>LoginViewMediator</code> you&#8217;ll see the following method:
<pre class="brush: as3;">
public function get view():LoginView
{
return this._view as LoginView;
}
</pre>
<p>Put this into method into each concrete VM with it&#8217;s corresponding view type and you&#8217;re good to go! Problem solved.</li>
<li>We check to see if the view has been <a href="http://livedocs.adobe.com/flex/3/langref/mx/core/UIComponent.html#initialized" target="_blank">initialized</a>, ie, has the creationComplete event fired and can I start to work with children components of this view without getting runtime errors. If it has, then we call the init() method (which can and should be overridden by concrete VMs to initialize themselves); if not, then we listen for the creationComplete event and call the <code>init()</code> method then and only then. This ensures that when we want to set event handlers and data bindings on the view&#8217;s children we know they exist and we don&#8217;t hit nulls leading to runtime errors.</li>
<li>Finally, if you look at the <code>init()</code> method in the AbstractViewMediator, you&#8217;ll see that it also calls the <code>setViewListeners()</code> and <code>setViewDataBindings()</code> methods &#8212; these are placeholder methods where developers can again add concrete event handlers and data bindings in VM subclasses by overriding them.</li>
</ol>
<p>The last thing the AbstractViewMediator does is provide the event dispatcher class member variable that we discussed earlier: <code>public var eventDispatcher:IEventDispatcher;</code></p>
<p><strong>Controllers &amp; Delegates</strong></p>
<p>In Swiz, we eliminate the idea of a Command class (from Cairgorm) and kind of replace it with the controller &#8212; I say kind of b/c it&#8217;s not exact mapping as the Cairngorm Command follows the actual J2EE Command design pattern whereas Swiz uses a controller to handle events from the UI to make service calls, act as a responder for the service calls, and finally to orchestrate what happens in the app after the service call (usually by dispatching an event). Since we already looked at the event mediation of the in the <code>LoginController</code> we won&#8217;t discuss that, but we will dig into how the controller leverages a corresponding LoginDelegate to call the service and perform data transformations on the service&#8217;s response object. So let&#8217;s look at the internals of the actual login event mediation in the <code>LoginController</code>:</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;login&amp;quot;, properties=&amp;quot;dto&amp;quot; )]
public function login( dto:LoginDTO ):void
{
logger.debug(&amp;quot;login&amp;quot;);

var call:AsyncToken = this.delegate.login(dto);

// I created 2 ways to handle the login service delegate
// you can either have the result come back to the controller
// or you can catch the result in the delegate and have it perform
// the necessary data transformations (traditional approach) before
// kicking it back to this controller via an event

// APPROACH 1) have the results come back directly to this controller
//this.executeServiceCall(call, onLoginResult, onLoginFault);

// APPROACH 2) have the results come back the delegate for data transformations
// before coming back to this controller
this.executeServiceCall(call, this.delegate.result, onLoginFault);
}
</pre>
<p>Out of the box, Swiz recommends that the controller handle the actual service response and data transformations before deciding what the app should do next&#8230;that&#8217;s too much responsibility for one object in my opinion, so as you can see I decided to allow the <code>LoginDelegate</code> to handle the actual service response: <code>this.executeServiceCall(call, this.delegate.result, onLoginFault);</code>. After the delegate finishes with the response, it dispatches an event:</p>
<p><strong>LoginDelegate</strong></p>
<pre class="brush: as3;">
public function result(resultEvent:ResultEvent):void
{
logger.debug(&amp;quot;result&amp;quot;);

var userModel:UserModel;
var xml:XML;
var dynEvt:DynamicEvent;

// get the response typed as desired
userModel = this.getTypedResponse(resultEvent);

// let something know that the login delegate is done
dynEvt = new DynamicEvent(&amp;quot;loginDelegateComplete&amp;quot;);
dynEvt.userModel = userModel;
this.eventDispatcher.dispatchEvent(dynEvt);
}
</pre>
<p>And then the event is mediated by the <strong>LoginController</strong> where it updates the necessary model properties and dispatches an event to signify the end of the login process.</p>
<pre class="brush: as3;">
[Mediate( event=&amp;quot;loginDelegateComplete&amp;quot;, properties=&amp;quot;userModel&amp;quot; )]
public function completeLogin(userModel:UserModel):void
{
logger.debug(&amp;quot;completeLogin&amp;quot;);

var role:String;

// populate the model with data from the response DTO
this.appModel.user = userModel;

// determine of user is an admin
for each ( role in userModel.rolesList )
{
if(role == RolesConstants.ROLE_ADMIN)
{
this.appModel.user.isAdmin = true;
break;
}
}

// set this last as this is what binds the view change
this.appModel.isUserAuthenticated = true;

var evt:DynamicEvent = new DynamicEvent(EVENT_LOGIN_COMPLETE);
this.eventDispatcher.dispatchEvent(evt);
}
</pre>
<p>I think that about covers it for this edition. Any questions?</p>
<p>More to come on Swiz in the future.</p>
<p align="left"><a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+1+http://cdi74.th8.us" title="Post to Twitter"><img class="nothumb" src="http://www.webappsolution.com/wordpress/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a class="tt" href="http://twitter.com/home/?status=Swiz+Passive+View+Example+%3A%3A+Part+1+http://cdi74.th8.us" title="Post to Twitter">Tweet This Post</a></p>]]></content:encoded>
			<wfw:commentRss>http://www.webappsolution.com/wordpress/2010/01/06/swiz-passive-view-example-part-1/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

