25
May 09

How to compare 2 dates in ActionScript

Date objects don’t have a built-in compare() method, but comparing dates  easy.Don’t  look at the Date objects , but rather the values represented by the objects using the Date.getTime() method:

Date.getTime() : Returns the number of milliseconds since midnight January 1, 1970, universal time, for a Date object. Use this method to represent a specific instant in time when comparing two or more Date objects.

This makes comparing dates as trivial as comparing numbers. Here’s a simple method that compares two dates, returning minus one (-1) if the first date is before the second, zero (0) if the dates are equal, or one (1) if the first date is after the second:

1
2
3
4
5
6
7
8
9
10
11
public function compare (date1 : Date, date2 : Date) : Number {
var date1Timestamp : Number = date1.getTime ();
var date2Timestamp : Number = date2.getTime ();
var result : Number = -1;
if (date1Timestamp == date2Timestamp){
result = 0;
} else if (date1Timestamp > date2Timestamp){
result = 1;
}
return result;
}

21
May 09

Flex regular expression cheatsheet

regular-expressions-cheat-sheet-v2

to see large version, right click save as image


21
May 09

Flex "Bindable" tag

the Bindable tag is widely used in flex and in simpleterms its used to bind an entity to other entity if there is a change in the source.
The tag can have the following form:

[Bindable]
public var foo;

The Flex compiler automatically generates an event named propertyChange for the property. If the property value remains the same on a write, Flex does not dispatch the event or update the property.

You can also specify the event name, as the following example shows:

[Bindable(event="fooChanged")]
public var foo;

In this case, you are responsible for generating and dispatching the event, typically as part of some other method of your class. You can specify a [Bindable] tag that includes the event specification if you want to name the event, even when you already specified the [Bindable] tag at the class level.

In order for binding to work you need to make sure changes to the data are known to the framework. Unlike most of dynamic languages implementations, ActionScript 3 is built for speed and heavily utilizes direct access to the properties and methods. In this situation the only way for data to notify the world about the changes is to embed the code to fire change events.

Flex compiler helps in a big way by introducing [Bindable] and [Managed] tags. If you prefix your variable with [Bindable] tag, compiler does the following:
1. Inspects every public property and setter of you variables class and generates wrapper getters/setters that adds event notification.
2. Every time “bindable” property is being used, compiler references these getters/setters instead of original properties


20
May 09

Remove “Flex Data Visualization Trial” using actionscript

I did a small hack in the Flex charting code and removed the Trial message from the Charting component by writing 1 simple actionscript lines.

what you need to do is in the creationcomplete of any charting component write the following code

1
2
3
4
5
6
7
8
9
private function removeTrialMsg():void{ 
          var arra : Array = new Array();
            for(var i:int =0;i<this.numChildren;i++){
               arra.push(this.getChildAt(i));
            }

// the above 4 lines are just to check  what r the childs added
(this.getChildAt(this.numChildren-1) as TextField).htmlText = " ";
}

we  tried to set visible false but that dint work we also tried to remove the textfield child alltogether  but that too dint work but finally it was the html text property of the textfield that gave way.

now you can also add your custom  trial message to your application :)

just replace the blank with your text for example:

1
2
3
private function removeTrialMsg():void{ 
      (this.getChildAt(this.numChildren-1) as TextField).htmlText = "this is TRIAL";
}

But its better that you buy your own licence key for charting. The above example was basically for educational purpose. have fun :)

trial


20
May 09

Flex Builder renamed

The upcoming version of the tool to build your flex applications is called Flash Builder! (formally known as Adobe Flex Builder). The flex framework will continue to be known as Flex. The naming is appropriate given the fact that every one who is building a Flex / Flash / AIR app today is building it on top of the “Adobe Flash Platform”

Welcome, Flash Builder!


08
Mar 09

launched exposedout v0.1b

I finally started launched exposedout. Its just the beta version for now, will change it as soon as i get time.

www.exposedout.com

Please leave your comments here :)


10
Feb 09

How to turn on debug trace in Flex

When you encounter issue wit your flex app, one useful tool for troubleshooting is to turn on debug in flex to get some output that will provide some clue of the cause of he problem. Here is how to turn it on from server-side as well as from client-side:

1. From server side:
In the services-config.xml, set the logging level to debug, and set filters to include the service you need:

<target class=”flex.messaging.log.ConsoleTarget” level=”debug”>
<properties>
<prefix>[Flex hotfix2] </prefix>
<includeDate>true</includeDate>
<includeTime>true</includeTime>
<includeLevel>true</includeLevel>
<includeCategory>true</includeCategory>
</properties>
<filters>
<pattern>Endpoint.*</pattern>
<pattern>Service.*</pattern>
<pattern>Protocol.*</pattern>
<pattern>Message.*</pattern>
<pattern>DataService.*</pattern>
<pattern>Configuration</pattern>
</filters>
</target>

See available pattern in doc:

http://livedocs.adobe.com/livecycle/8.2/programLC/programmer/lcds/help.html?content=services_logging_3.html

2. To turn on trace in JGroup:
in jgroups-tcp.xml, add <TRACE/> tag just before the </config> line :

<config>
….
<TRACE/>
</config>

3. To turn on from client-side:
Make sure flashlog.txt is enabled, i.e, have the following setting in mm.cfg
TraceOutputFileEnable=1
ErrorReportingEnable=1
See more details in the doc here
There is a good blog regarding mm.cfg here as well.
Then in your flex app, add the following tag:
<mx:TraceTarget/>

4. To turn on the flash player policy logging

see http://www.adobe.com/devnet/flashplayer/articles/fplayer9_security_05.html

Original post


22
Jan 09

Filter datagrid using a hslider

Here is an example of Data grid filtered using a H slider  with 2 thumbs to select the range of date for which to  filter the data grid. The combo box is used to select the specific column on which the filter has to be applied to. The check box is used to either enable or disable the filter functionality.

Screenshot:

testfilterdg

For source please read the complete article Continue reading →


16
Jan 09

FrameworkQuest 2008 Part 6: The Exciting Conclusion

FrameworkQuest Part 6 by Tony Hillerson
Find the original post here

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

Well kids, it’s been a wild ride. We’ve looked at five
implementations of a simple Twitter client built with no framework, Cairngorm,
PureMVC, Swiz, and Mate. We’ve talked about important things like pronouncing
the framework’s names, architectural patterns, Inversion of Control, and
programmer joy.

In this last part, I’m going to turn off any semblance of
objectivity and let you know what I think about these frameworks. If you’re not
interested in what I think, I don’t blame you, but I also don’t want anyone to
take my word for it and blindly choose which one I like. Take a look at the
examples and see which one you’d rather work with. Come up with a simple
application and build it four different way. In other words, try before you
buy.

Ok, here we go. First, in prose, and then with some numbers.

Cairngorm

As I mentioned early on, I’ve been using Cairngorm for a while
now. Does that make me want to stick with it or try something new? Well, I’ve
liked using Cairngorm. I also like to use Christophe
Herreman
‘s  Prana
to help out a bit with sequences of commands and IoC. In fact, I wanted to have
an article on Prana

in this series, but I just ran out of time. You can settle for this blog post about delegate factories, which shows
how we might have made our dummy data solution a little more palatable.

The thing I like most about Cairngorm is the command pattern. I
really like having commands that are named with a description of what they do,
and I really like that everything to do with getting that specific task done is
inside the command.

Cairngorm, though, being around the longest and the loneliest,
has attracted criticism. It’s surprising to me, because I think it’s not a bad
framework, and not even that heavyweight. Even so, I came into this article to
try out these other frameworks and see if one struck me as something I’d rather
work with from day to day. Let’s have a look at some criticisms.

Some people don’t like Cairngorm’s verbosity when it comes to
defining a new command. I don’t think there’s anything wrong there that can’t
be solved with some code generation, but I agree that it’s pretty
verbose.

Other arguments against Cairngorm are usually leveled against its
use of a Singleton model. A Singleton makes unit testing hard, and sometimes
people say it’s just a glorified "global variable". Let’s take these
one at a time.

Singletons are not "global variables". People make fun
of using global variables because it’s a rookie way of getting around building
a good architecture. It was the way we built Flash apps before we knew how to
program. That’s true – global variables are unsafe because there’s no guarantee
who’s accessing and changing them. In short, there’s no encapsulation. But with
a Singleton, there is encapsulation, because what you’re dealing with is still
an object. There’s nothing stopping you from using read-only getters instead of
public properties.

Singletons do, however, make it harder to unit test, because a
simple test that, say, runs a command sequence and tests that a property on the
model changed as expected, changes that model instance of which there is only
one. The more tests, the more the model gets into a strange initial state. I
think that’s not that big of a deal if you just take the time to reset the
model to a known state before each test. If you have to have a “logout” in your
app anyway, you’ll need to do something like that anyway (unless you cop out
and just refresh the page with javascript). I agree, though, that it’s extra
code to maintain.

One last problem people have is that Cairngorm has you putting
Cairngorm events on the view. That means you have to make a Cairngorm event,
first, and second it means that you have framework code on the view that makes
it hard to refactor away from Cairngorm.

Now, look. How many times in an app do you just scrap it and
switch frameworks? I never have. I agree that componentizing is great when you
really have a view you can turn into a blackbox component, but if you have a
view specific to a certain app I really don’t see that it’s anything but bikeshedding
to try to make the view code re-usable. There’s a point of diminishing returns,
and at that point or even a little before, you should just move on and get the
app done. That’s why I don’t care that much about Flex framework code in a Flex
application. I’m certainly open to the idea of using regular Flash events,
though, so that brings us to PureMVC.

PureMVC

One way I describe the difference between Cairngorm and PureMVC
to people is that Cairngorm doesn’t have much to say about your view code, and
PureMVC doesn’t have much to say about your service access code. That’s why you
see the BusinessDelegate pattern in PureMVC and Cairngorm – because it works
well.

What PureMVC tries to fix, though, is having the view cluttered
with PureMVC code. It fixes that well – the only place you have to put PureMVC
code is on the root application. As far as that goes, I like using Flash events
instead of Cairngorm events. What’s nice there is that if I’m using a blackbox
component that emits Flash events, I can still easily respond in a Mediator
whereas in Cairngorm I’d have to catch and re-dispatch an event as a Cairngorm
event if I wanted to take action.

One other important PureMVC goal is to be an Actionscript
framework, not a Flex framework. That means I can’t (or shouldn’t) use Flex
binding to wire up a view to a Proxy, I need to have the Mediator do it. Is
that a win? I think binding is great, and I also think it needs special
understanding to use it correctly. In a medium to large sized application, by
using binding right out of the box, you can cause a really huge event storm
whenever any bound property changes and bring performance to a halt.

I think binding is good when used responsibly, so when PureMVC
says to skip it, I’m interested, but I want to know what it costs to use. So
what I don’t like about PureMVC is how much boilerplate code there is. I like
the idea of a mediator for views, but there is so much set up to do. The
constants, the viewComponent
wrapper, listNotificationInterests,

handleNotification,
there’s a lot of stuff it takes to set up a Mediator. I like PureMVC in
general, but I’ve never gotten up the energy to use it on a project because of
inertia. It feels like it’s a big investment to do things the PureMVC way.

Contrast that with the lightest weight framework, Swiz.

Swiz

I have to be honest, when I wrote this article because of the
buzz and Laura’s presentation at 360 Flex San Jose, I
was really prepared to like Mate hands down. (BTW, here’s Chris’s presentation). When I
started using Swiz, though, I immediately felt the joy. You know what I’m
talking about – that sense that you’re in the groove and building something and
there’s not much work between having an idea and implementing it.

I’m going to make a distinction that I haven’t heard before, or
at least don’t remember hearing. I think there are proscriptive and prescriptive tendencies to software
frameworks. On the one hand, proscription means saying what you can’t do, and
on the other, prescription means saying what you could do. Whereas PureMVC says
a lot of things you shouldn’t do and some things that you can do, Swiz almost
completely sticks to saying what you can do.

Swiz leaves a lot up to you. All it does is provide some easy
ways to do things like inject a controller or a model into the view and to
easily wire up events with the Mediate metadata tag. From there on out, it’s up
to you. Swiz is the laissez faire framework, and I really like that.

The only thing is that all the service interaction stuff, the
dynamic delegates and command all expect you to be using RemoteObjects and
delegate methods that return AsyncTokens. I’m sure this could be fixed, but
unless I’m missing something until it is fixed Swiz is less useful to anyone
not using AMF services. Since I’m used to using RubyAMF,
that’s great for me, but I can’t always count on it or BlazeDS or ColdFusion
being on the server side. You can work around it, but it’d be nice to have
those tools available for other types of services.

One thing I’d also like to see is an easy way to use the command
pattern where logic is actually written in the commands. I really like that
pattern because I think it’s cleaner to have logic in commands instead of in
controller files that have to do with more than one type of data or view.
Controllers tend to get a little big, especially with callbacks.

That said, I really like Swiz and I think Autowire and Mediate
are enough incentive to use it over Cairngorm or PureMVC. Swiz is the style of
programming that those three frameworks represent done right. Mate, however, is
a different, hmm… what should I say… cup of tea?

Mate

Mate is picking up a lot of steam lately (these puns are going to
keep on coming, people, you may as well just laugh now). Everyone I talk to lately
loves it. I think it’s a shame that some of those people aren’t really getting
a chance to try Swiz too, but when you feel what it’s like developing with
Mate, you’ll see that it’s not that big of a shame.

The way I make a distinction between Swiz and Mate is that Swiz
is the Cairngorm style done right, while Mate is a completely different style.
The big difference, I think, is the declarative versus programmatic style of
Mate. Since a lot of what we do in Flex is in MXML, using MXML to set up framework
interaction makes a lot of sense, and also just seems to really fit alongside
the view code.

PureMVC and Mate both want you to use regular old Flash events
instead of framework prescribed events. Swiz wants that too, but sometimes you
need to dispatch through its dispatch system. What makes Mate so elegant,
though, was the insight of just using the event-bubbling to catch them with the
EventMap without defining a bunch of wiring code. Of course, that breaks down
when you want to use a service delegate and have to pass in the dispatcher, but
it doesn’t break down as hard as Swiz breaks down when you don’t use
RemoteObjects.

Mate is also really flexible. There are probably more tools there
than you need, and not only that, it has a plugin
structure
. I don’t understand it yet, but that’s kind of nice. I
also like that Mate has a way of using Commands, although I’m not sure it would
be worth it to just turn your EventMap into a Cairngorm FrontController.

I like Mate a lot and I can’t find anything to pick on. Really.
The only thing is I don’t think I fully understand how it scales, and the way
it does view and object cacheing is a little bit of magic. Magic isn’t bad, but
again, I just don’t know what pitfalls await me while using it. I hope to find
out, though, and I’m really excited to use Mate.

Framework Smackdown

Now is the time when I give you my subjective rating system to
give a bit more quantification. Below is a table rating the frameworks on five
variables from 1-5, 5 being high:

1.    Conciseness – How little it takes to get something done in the
framework.

2.    Familiarity – Once you get past the initial learning phase, how
easy is it to fall into the pattern of using the framework. How easy is it to
think in the framework?

3.    Flexibility – How easy it is to work with exceptions to normal
development patterns.

4.    Power – The tools to get the job done

5.    Programmer
Joy
– Is it fun to use the framework? Is
it rewarding, or does it punish you when you have to use it?

Conciseness

Familiarity

Flexibility

Power

Joy

Total

Cairngorm

2

4

4

3

3

16

PureMVC

1

2

5

3

1

12

Swiz

5

5

2

2

4

18

Mate

4

4

4

5

5

22

Well, there you have it, folks. I’m riding into this one with
flame-proof-pants on, but I hope I’ve done a little good by giving the
reasoning behind my thinking. I welcome any critique of my reasoning, and if
there’s a better way to do something in my example code please put comments on
the code in Github and leave a note here as well. I hope
the example applications help, and I hope that you’ve all learned a little bit
about yourselves on this journey. Viva Flex.

Read more from
Tony Hillerson
.


16
Jan 09

FrameworkQuest 2008 Part 5: Mate, the Pure MXML Framework

FrameworkQuest Part 5 by Tony Hillerson
Find the original post here

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

Let’s get this out of the way first thing. It’s Mah-tay, not
M-eight. Like the drink, the creators of Mate, Nahuel Faronda and
Laura Arguello
, come from Argentina. If you’ve never tried Mate (the
drink), you should – it’s tasty. If you’ve never tried Mate

(the framework), well, that’s tasty, too, and you’re about to dig into a big
bowl full. Sorry about that mixed metaphor there.

Mate is design to take advantage of MXML and regular old Flash
events dispatched the regular way, not through the framework like Cairngorm or
Swiz (although Swiz is open to regular event dispatching if you set it up
yourself). In that way it’s like PureMVC. But Mate uses the fact that part of
the framework is defined right at Application level to make the event-driven
part of the framework very unobtrusive and easy.

Since it’s very unobtrusively event based (you’ll see what I mean
in a bit) it allows you to make a very componentized application easily, and
although of course you can use the classes from the framework in ActionScript
form, you’ll be surprised at how much you can do right in MXML.

Let’s look at one of those green box things again. The Delegate is yellow to
show that it’s optional.

So when a user interacts with the view, and event is fired. The EventMap, declared on
the root application receives all events dispatched anywhere in the view as
long as the bubbles
property of the event is set to true. So the basic way of acting on some user
input is to dispatch a custom event with the bubbles property set to true. This is
how Mate is so unobtrusive. You don’t have to define event listeners all over
the place, just define some code in the EventMap to catch certain types of
events. The EventMap
takes care of calling the service in simple situations, but it could delegate
the service call to a delegate as well.

The EventMap
could also fire off a command, Cairngorm style, if you
like that way of doing things better. Mate is a very flexible framework. In
fact, there are a lot more parts to Mate than are listed here and any of them
could be used to do things a different way or to deal with exceptions. Mate’s
documentation is particularly good and easy to use compared to the other
frameworks, so have a look at it if you want.

To get data into the view, Mate either defines an IoC style Injector or simply
dispatches an event with an EventAnnouncer
and the view can use Mate’s Listener
tag to be notified of these events. We’ll see both ways of doing things.
Storing data in the model is delegated to objects that most of the examples
call Managers.
Some examples use a Manager
to actually do service interaction. Again that’s up to you and how pure you
want the model to be.

Ok, let’s start looking into how I did this application the Mate
way.

Twitter Through A Bomba

The first Mate specific code in our app is on the root
application.

twitteria_mate/src/twitteria_mate.mxml #21

1
2
<pre>
&lt;maps:MainEventMap /&gt;</pre>

The EventMap
is central to any Mate application, so it’s defined early. Note that although
we only have one, you can have as many as you want, so you can break things up
as clean as you want them.

Each application defines its own EventMap, and ours is imaginatively
called MainEventMap.
There’s not a lot more to see on the application, so let’s look at logging in.

Logging In

Once again, hitting enter in the password field kicks off the
login process. It calls the login
method on LoginView.

twitteria_mate/src/com/insideria/twitteria/view/LoginView.mxml
#10-13 (formatted)

1
2
3
4
5
6
7
8
<pre>
<span class="category1">public</span> <span class="category1">function</span> login():<span class="category1">void</span> {
      <span class="category1">var</span> <span class="category1">le</span>:LoginEvent = <span class="category1">new</span> LoginEvent(
           usernameText.<span class="category2">text</span>, passwordText.<span class="category2">text</span>

      );
      dispatchEvent(<span class="category1">le</span>);
}</pre>

We dispatch a LoginEvent
and send along the username and password. Nothing framework specific. Let’s
look at the LoginEvent.

twitteria_mate/src/com/insideria/twitteria/events/LoginEvent.as
#7-16 (formatted)

1
2
3
4
5
6
7
8
9
10
11
12
<pre>
<span class="category1">public</span> <span class="category1">static</span> const LOG_IN:<span class="category2">String</span> = "<span class="quote">login</span>";


<span class="category1">public</span> <span class="category1">var</span> username:<span class="category2">String</span>;
<span class="category1">public</span> <span class="category1">var</span> <span class="category2">password</span>:<span class="category2">String</span>;

<span class="category1">public</span> <span class="category1">function</span> LoginEvent(username:<span class="category2">String</span>, <span class="category2">password</span>:<span class="category2">String</span>) {
      <span class="category1">super</span>(LOG_IN, <span class="category1">true</span>, <span class="category1">false</span>);
      <span class="category1">this</span>.username = username;
      <span class="category1">this</span>.<span class="category2">password</span> = <span class="category2">password</span>;
}</pre>

First, we keep a constant on the event to make sure the type of
the event is clear. We also have a place for the username and password payload. The super call is
important. The arguments are ‘type’, ‘bubbles’, and ‘cancelable’. The type is
our constant, and bubbles is set to true. That’s important because when an
event bubbles it moves all the way to the top of the display object tree and
anything in the tree can listen for it. The EventMap ultimately listens for this
event.

twitteria_mate/src/com/insideria/twitteria/maps/MainEventMap.mxml
#13-16 (formatted)

1
2
3
4
5
6
7
8
9
10
11
12
<pre>
&lt;EventHandlers <span class="category2">type</span>="<span class="quote">{LoginEvent.LOG_IN}</span>" debug="<span class="quote">true</span>"&gt;

     &lt;ObjectBuilder
          generator="<span class="quote">{TwitterDelegate}</span>"
          constructorArguments="<span class="quote">{[
               event.username, event.password, scope.dispatcher
          ]}</span>" /&gt;
     &lt;MethodInvoker
          generator="<span class="quote">{TwitterDelegate}</span>"
          <span class="category1">method</span>="<span class="quote">loadTimeline</span>" /&gt;
&lt;/EventHandlers&gt;</pre>

Wow. There’s a lot going on here, so let’s break it down. The EventHandlers tag
defines the actions to take for a certain type of event, designated in the type property. This
corresponds to the constant in our LoginEvent, so this is the event handler for when that
event bubbles up.

When that event gets caught, the first tag takes over. The ObjectBuilder
tag creates an object of a certain type, which is set in the generator property. That can be either
a fully qualified path as a string, or a class in a binding, like we have. The
default behavior is to create an object of that type and keep a reference to it
indexed by type. That means that any another object of that type is requested,
the cached object will be returned. This is how Mate deals with the problem
that Cairngorm deals with using singletons, that of keeping an instance of an
object easy to get to.

The constructorArguments
are, of course, how you pass in arguments to the class’ constructor. Here we
pass in, from the incoming event, the username, password, and from the scope property of the

EventMap, a dispatcher. Hopefully
the event properties are clear enough to you. The dispatcher thing needs to be
cleared up a bit though, I bet. What we’re going to do, since we don’t have a
standard service to call, like a RemoteObject, WebService, or HTTPService, which all have invokers in Mate, is to have a delegate that
dispatches events when things happen. To make that work with any Mate Listeners, which
we’ll see in a bit, we need to dispatch the events through Mate. This dispatcher passed
into the TwitterDelegate’s

constructor lets us do that.

Next, we use a MethodInvoker
tag to invoke a method on the TwitterDelegate,
namely loadTimeline.
The MethodInvoker
uses the same generator style. Since the defaults are in place on the ObjectBuilder, the
object that was built there will be reused here. In fact, We didn’t even really
need to use the ObjectBuilder,
because the generator in MethodInvoker

would have cached the class too. That’s the default behavior of most of the
tags used in the EventMap.
Why did I use the ObjectBuilder
then? Just to show it could be done and to make it explicit. Look, I’m trying
to teach here.

That was a lot of explanation for two or three tags, so let’s say
it in plain English. When the EventMap
gets the LoginEvent,
it builds a TwitterDelegate

and caches the instance for whenever another TwitterDelegate is requested. Then we
invoke loadTimeline
on a TwitterDelegate,
which uses the cached instance. Let’s see what happens in the delegate.

Loading The Timeline

Just like before, we decide on using the dummyData or not, and possibly call
the Twitter service.

twitteria_mate/src/com/insideria/twitteria/business/TwitterDelegate.as
#33-42 (formatted)

1
2
3
4
5
6
7
8
9
10
11
12
<pre>
<span class="category1">public</span> <span class="category1">function</span> loadTimeline():<span class="category1">void</span> {
      <span class="category1">if</span> (useDummyData) {
            <span class="category1">var</span> te:TwitterEvent = <span class="category1">new</span> TwitterEvent(
                 TwitterEvent.ON_FRIENDS_TIMELINE_RESULT
            );
            te.<span class="category2">data</span> = getDummyData();
            friendsTimelineLoaded(te);
       } <span class="category1">else</span> {
            twitterService.loadFriendsTimeline(username);
       }
}</pre>

And either way, the callback is executed.

twitteria_mate/src/com/insideria/twitteria/business/TwitterDelegate.as
#53-56 (formatted)

1
2
3
4
5
6
<pre>
<span class="category1">private</span> <span class="category1">function</span> friendsTimelineLoaded(te:TwitterEvent):<span class="category1">void</span> {
      <span class="category1">var</span> e:TimelineReceivedEvent =
           <span class="category1">new</span> TimelineReceivedEvent(te.<span class="category2">data</span> as <span class="category2">Array</span>);
      dispatcher.dispatchEvent(e);
}</pre>

This time it’s different, though, and we get together a TimelineReceivedEvent
with the array of tweets and dispatch it through the dispatcher we got from the
MainEventMap
when the delegate was constructed.

The MainEventMap

is listening for that kind of event:

twitteria_mate/src/com/insideria/twitteria/maps/MainEventMap.mxml
#18-21 (formatted)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<pre>
&lt;EventHandlers
     <span class="category2">type</span>="<span class="quote">{TimelineReceivedEvent.TIMELINE_RECEIVED}</span>"
     debug="<span class="quote">true</span>"&gt;

     &lt;MethodInvoker
          generator="<span class="quote">{TwitterManager}</span>"
          <span class="category1">method</span>="<span class="quote">setCurrentTweets</span>"
          <span class="category2">arguments</span>="<span class="quote">{[event.tweets]}</span>" /&gt;
     &lt;EventAnnouncer
          generator="<span class="quote">{ViewStateEvent}</span>"
          <span class="category2">type</span>="<span class="quote">{ViewStateEvent.SHOW_MAIN_VIEW}</span>"
          bubbles="<span class="quote">true</span>" /&gt;

&lt;/EventHandlers&gt;</pre>

When it gets it, it invokes setCurrentTweets on a generated TwitterManager and
passes the tweets we set on the event. It then uses an EventAnnouncer
to fire a ViewStateEvent

of type ViewStateEvent.SHOW_MAIN_VIEW.
Let’s take those one at a time.

The TwitterManager
is our model-type object, following what I take to be a Mate naming convention.
It’s simple enough.

twitteria_mate/src/com/insideria/twitteria/business/TwitterManager.as
#5-12 (formatted)

1
2
3
4
5
6
7
8
<pre>
<span class="category1">public</span> <span class="category1">class</span> TwitterManager {
      [Bindable]
      <span class="category1">public</span> <span class="category1">var</span> currentTweets:ArrayCollection;

      <span class="category1">public</span> <span class="category1">function</span> setCurrentTweets(tweets:<span class="category2">Array</span>):<span class="category1">void</span> {
            currentTweets = <span class="category1">new</span> ArrayCollection(tweets);
       }</pre>

It just has a Bindable collection of tweets and a way to set them. Now
that they’re set, how do they get to the view? A PropertyInjector, with the help of Flex
binding.

twitteria_mate/src/com/insideria/twitteria/maps/MainEventMap.mxml
#31-33 (formatted)

1
2
3
4
5
6
7
8
<pre>
&lt;Injectors <span class="category2">target</span>="<span class="quote">{MainView}</span>"&gt;
     &lt;PropertyInjector
          source="<span class="quote">{TwitterManager}</span>"
          sourceKey="<span class="quote">currentTweets</span>"
          targetKey="<span class="quote">currentTweets</span>" /&gt;

&lt;/Injectors&gt;</pre>

This is another very Mate way of doing things. This is saying
that Mate should bind the currentTweets
property of any cached TwitterManager
into the cached MainView
instance’s currentTweets.
Hold on, when did a MainView

get cached? Well, as a service to the user, Mate listens for the event from any
view (I believe the creationComplete
event) just like it does for any other user defined bubbling event, and then
caches a reference to that view. That way the EventMap has a way to communicate with
the view of any type. Sneaky, eh? I thought so. Now whenever the currentTweets on our
manager changes, that view will be updated. Now we have the data getting to the
right view, but how do we get the ViewStack on the application onto the right index?

That second tag, the EventAnnouncer fires off a ViewStateEvent.

twitteria_mate/src/com/insideria/twitteria/events/ViewStateEvent.as
#7-11 (formatted)

1
2
3
4
5
6
7
8
9
<pre>
<span class="category1">public</span> <span class="category1">static</span> const SHOW_MAIN_VIEW:<span class="category2">String</span> = "<span class="quote">showMainView</span>";

<span class="category1">public</span> <span class="category1">function</span> ViewStateEvent(
                               <span class="category2">type</span>:<span class="category2">String</span>,
                               bubbles:<span class="category2">Boolean</span>=<span class="category1">true</span>,
                               cancelable:<span class="category2">Boolean</span>=<span class="category1">false</span>) {
      <span class="category1">super</span>(<span class="category2">type</span>, bubbles, cancelable);
}</pre>

Since we’re using the EventAnnouncer to fire this off, it needs the standard
event constructor. Also, we could have lots of view state constants to use for
different view state events since Flash events are unique by sort of a weird
mix of class and type property. So where does this event go? Well, if we look
back on the application, we’ll see.

 

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

1
2
3
4
<pre>
&lt;mate:Listener
     <span class="category2">type</span>="<span class="quote">{ViewStateEvent.SHOW_MAIN_VIEW}</span>"
     <span class="category1">method</span>="<span class="quote">showMainView</span>" /&gt;</pre>

Here’s a Listener

tag that listens for just that event type. When it gets it, it calls showMainView.

twitteria_mate/src/twitteria_mate.mxml #7-12

1
2
3
4
5
6
7
8
<pre>
<span class="category1">public</span> const LOGIN_VIEW:<span class="category1">int</span>    = 0;

<span class="category1">public</span> const MAIN_VIEW:<span class="category1">int</span>     = 1;

<span class="category1">private</span> <span class="category1">function</span> showMainView(e:Event):<span class="category1">void</span> {
      mainViewStack.selectedIndex = MAIN_VIEW;
}</pre>

That method sets the view stack to where it should be. Now we
have the MainView
showing in the ViewStack
and right data in the list in MainView.
Let’s have a look at setting status now.

Setting Status

As you probably can guess, we set status by firing off an event.
Here’s where we do it:

twitteria_mate/src/com/insideria/twitteria/view/MainView.mxml
#12-16

1
2
3
4
5
6
<pre>
<span class="category1">private</span> <span class="category1">function</span> setStatus():<span class="category1">void</span> {
      <span class="category1">var</span> e:SetStatusEvent = <span class="category1">new</span> SetStatusEvent(statusText.<span class="category2">text</span>);
      dispatchEvent(e);
      statusText.<span class="category2">clear</span>();
}</pre>

And here’s where it ends up:

twitteria_mate/src/com/insideria/twitteria/maps/MainEventMap.mxml
#23-25 (formatted)

1
2
3
4
5
6
7
8
<pre>
&lt;EventHandlers <span class="category2">type</span>="<span class="quote">{SetStatusEvent.SET_STATUS}</span>" debug="<span class="quote">true</span>"&gt;

     &lt;MethodInvoker
          generator="<span class="quote">{TwitterDelegate}</span>"
          <span class="category1">method</span>="<span class="quote">setStatus</span>"
          <span class="category2">arguments</span>="<span class="quote">{[event.statusText]}</span>" /&gt;
&lt;/EventHandlers&gt;</pre>

We call setStatus
on the cached TwitterDelegate,
passing in the statusText
from the incoming event.

twitteria_mate/src/com/insideria/twitteria/business/TwitterDelegate.as
#58-61

1
2
3
4
5
<pre>
<span class="category1">private</span> <span class="category1">function</span> statusSet(te:TwitterEvent):<span class="category1">void</span> {
      <span class="category1">var</span> e:StatusSetEvent = <span class="category1">new</span> StatusSetEvent();
      dispatcher.dispatchEvent(e);
}</pre>

When the delegate is done, it dispatches a StatusSetEvent through
its dispatcher.

 

twitteria_mate/src/com/insideria/twitteria/maps/MainEventMap.mxml
#27-29 (formatted)

1
2
3
4
5
6
7
<pre>
&lt;EventHandlers <span class="category2">type</span>="<span class="quote">{StatusSetEvent.STATUS_SET}</span>" debug="<span class="quote">true</span>"&gt;

     &lt;MethodInvoker
          generator="<span class="quote">{TwitterDelegate}</span>"
          <span class="category1">method</span>="<span class="quote">loadTimeline</span>" /&gt;
&lt;/EventHandlers&gt;</pre>

Back in the EventMap,
it catches that event and reloads by calling back to the delegate, which kicks
off that whole chain again.

Next Up

Mate’s sort of a different beast from the other frameworks. The EventMap approach is
novel, as is the class caching. Once you see how it works, it’s a lot of fun to
use, though.

Now we’ve built our application using four different Flex
frameworks. Again, although it wasn’t an exhaustive look at each framework or
its capabilities, and since our use cases may have been a little out of the
ordinary especially around the delegate area, I hope that this has at least
shown you how it feels to use these frameworks in a day-to-day setting.

Next up, we’re going to get into the opinion section of the app,
where I tell you how I think each framework stacks up against the others, which
one I’d like to use from now on, and which one I think renders the most
Programmer Joy.

Read more from
Tony Hillerson
.


Pages: Prev 1 2 3 4 5 6 7 Next