2011-01-02

Parsley Framework Basics

After studying the Parsley framework lately, I obviously decided to created a mini-application to learn the basics of how the framework operates. And I've decided to share that here. Some concepts like custom Events and Commands will seem familiar if you have used the Cairngorm framework in the past.

Note: Some code omitted for brevity.

Creating View and Presentation Model
Our mini-application will simply display a list of Contacts in a DataGrid that is loaded from a remote source. So needless to say, create an MXML file (Contacts.mxml) that contains a DataGrid control with appropriate settings. The next part is important...no Script blocks! The whole point of the Parsley framework is to put all UI business logic in Presentation Model class, so unit testing is easy.

So the next step is to create the Presentation Model class called ContactsPM. This class should extend EventDispatcher (to be explained later), have a bindable field called contacts of type ArrayList and contain an empty method called search()... like so:

public class ContactsPM extends EventDispatcher {
[Bindable]
public var contacts:ArrayList;

public function search():void {}
}

The last part is to go back into your MXML view file (Contacts.mxml) and add two things. First, declare a bindable instance of the ContactsPM class you just created and also add the [Inject] metadata tag to it, like so:

[Inject]
[Bindable]
public var model:ContactsPM;

The [Inject] metadata tag will be used by Parsley to set an instance of the class when the framework initializes. Secondly, bind the contacts field of the ContactsPM class to the dataProvider of the DataGrid, such that when the contacts are set, the DataGrid will display them. Example is as follows:

<mx:DataGrid dataProvider="{model.contacts}"/>

So far, we have setup our view to use our Presentation Model class to display a list of contacts. How this will actually happen, comes next.

Creating custom Event and Command
The next steps are much like what you would do if you were using the Cairngorm framework. We will dispatch an Event that will in-turn execute a Command to retrieve our contacts. And in the case of Parsley, this is easier cause there are no classes to extend or interfaces to implement (is this better or worse? for you to debate).

First, create the GetContactsEvent class that extends the Flex Event class and simply calls the super constructor with the event name to set. Like so:

public GetContactsEvent extends Event {
public function GetContactsEvent() {
super( "getContacts" );
}
}

Next we need to create the GetContactsCommand class. It must declare two injectable fields, one for the remote object to use and another for the Presentation Model class (ContactsPM) we created earlier. Again, Parsley will set the values on these fields when the Command class is initialized. Example:

[Inject] public var service:RemoteObject;
[Inject] public var model:ContactsPM;

Then we need our command class to declare two methods. First, the execute method that takes our event class as a parameter and calls the remote Java method (notice the [Command] metadata tag that tells parsley which method to call when the event is fired):

[Command]
public function execute( event:GetContactsEvent ):AsyncToken {
return service.getContacts() as AsyncToken;
}

Secondly, a result method that takes an ArrayList as a parameter and sets it on our model so that the view will refresh itself (notice the [CommandResult] metadata tag that tells parsley which method to call once the remote call returns).

[CommandResult]
public function onResult( items:ArrayList ):void {
model.contacts = items;
}

Note: You can also declare a fault method for handling any failures.

Dispatching the Event
Now that we have created certain parts of our application, we need to connect them together, basically how to fire the command when our custom event is fired. Well remember the search() method in our Presentation Model class (ContactsPM) which we left empty earlier? Well time to fill it up with:

public function search():void {
dispatchEvent( new GetContactsEvent() );
}

Next, you need to add some metadata atop the ContactsPM class so that Parsley is aware that it will broadcast this event. This done by adding the following to the top of the class declaration:

[Event(name="GET_CONTACTS", type="demo.commands.GetContactsEvent")]
[ManagedEvents(names="GET_CONTACTS")]
public class ContactsPM extends EventDispatcher {
...
}

The last thing to do is to call the search() method once a button is pressed, as an example. Because the ContactsPM class extends EventDispatcher and the metadata information that was just added, the dispatch() method will use Flex's internal event mechanism to fire the event and then Parsley will take of calling the appropriate method on the appropriate class - in this case the execute method in the command class.

Configuring Parsley
Now the last part of our exercise is to create our Parsley configuration so that it can properly initialize the classes we have created and make our application work.

Creating Parsley configuration file
Like in the world of Spring, we must create a configuration file were all the objects that we need Parsley to manage will be declared. This will be in done in a simple MXML file (ContactsParsleyConfig.mxml):

<Objects xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
xmlns="http://www.spicefactory.org/parsley"
xmlns:dom="demo.domain.*"
xmlns:cmd="demo.commands.*">
<fx:Declarations>
<dom:ContactsPM />

<cmd:GetContactsCommand/>

<mx:RemoteObject id="contactManager" destination="contactManager"/>
</fx:Declarations>
</Objects>

The root tag of this MXML file is the Objects class that is defined by Parsley. Then we declare the Presentation Model class (ContactsPM), the command class (GetContactsCommand) and finally the RemoteObject class that the will be called by the command (in my demo it refers to a Java class).

Notice none of the declared objects have identifiers (id), but for such a small demo, this is not needed. More on that in future blog post :) .

Initializing Parsley
Now only two more changes remain to be done. In our root Application MXML file, we need to tell Parsley to load our configuration file. You do this by using Parsley's ContextBuilder tag as follows:

<s:Application xmlns:sf="http://www.spicefactory.org/parsley">
...
<fx:Declarations>
<sf:ContextBuilder config="ContactsParsleyConfig"/>
</fx:Declarations>
...
</s:Application>

And the final change is to add a single tag to the view (Contacts.mxml) component created earlier to tell it that it is part of the Parsley setup and will need to configured by Parsley when initialized - remember the view has the Presentation Model class as an injectable property:

<mx:VBox xmlns:sf="http://www.spicefactory.org/parsley">
...
<fx:Declarations>
<sf:Configure />
</fx:Declarations>
...
</mx:VBox>

And folks that's it. If anyone needs the actual demo source, please let me know and I will be happy to send them to you. I will be writing more about Parsley in the New Year as I learn more, with some some advanced posts and maybe some tips and tricks.

Until then, Happy New Year to all!

47 comments:

Anonymous said...

hey...can u please send me source code as i am trying to setup an project using parsley but i am getting "Instance must not be null"
Following is my main application.mxml and have blank config file.

Anonymous said...

can you please send me code. my id is soniya.cool2009@gmail.com

Anonymous said...

"And I've decided to share that here", it's not exactly shared:) Do you not put any actual swf's or running examples on your site?

Anonymous said...

I am in the process of evaluating framework. It would be helpful if you share your code with me. Thanks
tsamy@hotmail.com

Anonymous said...

hi, i am checking out this framework, nice if u could mail me the code zip.
email - sabinyoj@yahoo.com.
just a query - does it work well with
flex modules.

thanks.

Anonymous said...

Wouldn't it be easier to post the code?

Abhik said...

Hi,

Can you please send me the demo code?

Thanks,

Abhik

Anonymous said...

Dimitrios,

Could you please send the code to
ikagansky@yahoo.com

Thank you.

Anonymous said...

Hi Dimitry,
Could you please share the code for this? You can send it my id: praveen.ronnie7@gmail.com.

Thanks

Bijender Vashist said...

Great Post.
Can you please share the post.My mail id is vashistbijender82@gmail.com

Santiago Tamagno said...

Great post,

can any one send me the complete source of this example (santiagotanagno@gmail.com). thanks a lot!

Anonymous said...

why do you need source code? This is very well explained. Maybe you need to learn more flex first

flex developer said...

would you please share source code with me so i have better idea...Thanks

Jai said...

Hi,

Very impressive post. Exactly what I was looking for. Can you please send me the source also (jai.chandra@gmail.com). Also what to have your opinion and if we should be using a delegate pattern here for services or if its not required.

Thanks,
Jai

Anonymous said...

Hi
This article is very informative. Can you please send the source code to
shameersalim@gmail.com

Thanks
Shameer

Anonymous said...

It's remarkable for me to have a website, which is valuable for my knowledge. thanks admin

my blog - easy diets that work

Anonymous said...

So what are the farmacia on line results that men should
have a blood test, however if the condition is untreated, within a minute or two
of salt. What Does anfarmacia on line Offer? In day to day if you've got the aforementioned Home button in a stylized red circle just so it's
extra hard to miss, and an excellent social networking aggregation service.
The clients can use the touchscreen to hover or select each
of the five inventories has 20 questions. It would appear that in Britain, with the word" rock" are also acceptable.



Here is my site - 10.radabg.com

Anonymous said...

There are at least mini-markets as well as table decoration for the wedding occasion and as
the name of" Direct Car Excess Insurance". This should not reduce the money supply,
coupled with reduction of velocity as companies and individuals with loans that are attached to deposits battle it out with the bathwater.


Check out my website veteranjournal.com

Anonymous said...

paphos car hire marriages service by Direct Traveller.
They will also receive free car service to any part of paphos car hire.
It will be much more financially-savvy, this agency that makes you feel quite at home.

Anonymous said...

He put smiles on millions of faces when he helped invent farmacia on line.
Two Britons were detained in the UK had been
similar to average, it would behoove you to also look straight ahead at the man or woman above 65 a
long time.

Review my website; www.basata.com

Anonymous said...

Quality content is the key to be a focus for the people to pay a visit the web page, that's what this web site is providing.

Check out my blog post golf courses posters

Anonymous said...

Hi! This is my first visit to your blog! We are a collection of volunteers and starting a new
project in a community in the same niche. Your blog provided us beneficial information to work on.
You have done a wonderful job!

Feel free to visit my site :: chiropractic tools catalog

Anonymous said...

Heya! I'm at work surfing around your blog from my new iphone 4! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the great work!

My homepage www.journalhome.com

Anonymous said...

When I originally commented I clicked the "Notify me when new comments are added" checkbox and
now each time a comment is added I get several e-mails with the
same comment. Is there any way you can remove people from that service?
Many thanks!

my web blog: chiropractor-orlando.com

Anonymous said...

I used to be able to find good advice from your blog posts.



Feel free to surf to my website: Las Vegas Golf Schools

Anonymous said...

I'm impressed, I must say. Seldom do I encounter a blog that's both educative and entertaining, and let me tell you, you've hit the nail on the head. The problem is something which too few men and women are speaking intelligently about. I am very happy that I found this during my hunt for something relating to this.

My weblog Ladies Golf Gloves

Anonymous said...

Hi it's me, I am also visiting this web site daily, this website is really pleasant and the visitors are really sharing good thoughts.

My site St Cloud Florist

Anonymous said...

We stumbled over here coming from a different website and thought I should check things out.

I like what I see so i am just following you. Look forward to looking over your web page again.


Check out my web blog; http://www.yellowusa.Com

Anonymous said...

Hurrah, that's what I was seeking for, what a stuff! present here at this blog, thanks admin of this site.

My web-site what types of chiropractic care are there

Anonymous said...

Hey there would you mind sharing which blog platform you're working with? I'm planning
to start my own blog in the near future but I'm having a hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style seems different then most blogs and I'm looking for something completely unique.
P.S Apologies for getting off-topic but I had to ask!

Have a look at my website :: Outdoor Led Lighting

Anonymous said...

WOW just what I was searching for. Came here by searching for mothers
day john roberts

Here is my web-site: http://Web1.Lkmunmorah-H.Schools.Nsw.Edu.au/moodle/user/view.php?id=16503&course=1

Anonymous said...

Quality articles or reviews is the crucial to invite the
viewers to pay a visit the site, that's what this web site is providing.

My web-site ... funpro1000.homedns.org

Anonymous said...

Good day! I could have sworn I've been to this site before but after looking at some of the posts I realized it's
new to me. Anyhow, I'm certainly happy I discovered it and I'll be bookmarking it and checking
back regularly!

Visit my web blog; wiki.iteach.Kz

Anonymous said...

There's definately a lot to learn about this subject. I love all the points you made.

My web-site: masterssystems.com

Anonymous said...

After looking at a few of the blog posts on your website, I really appreciate your
way of blogging. I saved it to my bookmark website list and will be checking back in the near future.
Please visit my web site too and let me know what you think.


Also visit my homepage ... wiki.dev.simbs.com

Anonymous said...

you are in reality a just right webmaster.

The website loading pace is incredible. It sort of feels that you are doing any distinctive trick.
Also, The contents are masterwork. you have done a excellent process in this subject!


Feel free to visit my blog post Armitron Watches for Men

Anonymous said...

Thanks a bunch for sharing this with all of us you really realize
what you're speaking about! Bookmarked. Please additionally discuss with my web site =). We may have a link change contract between us

My web-site - women's relic watches

Anonymous said...

It's not my first time to go to see this web site, i am visiting this web page dailly and get good data from here everyday.

Here is my homepage: athletic injuries to the head neck and face

Anonymous said...

Heya! I know this is kind of off-topic however
I had to ask. Does operating a well-established
blog such as yours take a lot of work? I'm completely new to operating a blog but I do write in my diary on a daily basis. I'd like to
start a blog so I will be able to share my personal experience and
thoughts online. Please let me know if you have any kind of
ideas or tips for brand new aspiring bloggers. Appreciate it!


Here is my web page: short game instruction

Anonymous said...

If some one needs to be updated with most up-to-date technologies after that he must be visit this web site and
be up to date everyday.

My webpage men's vestal watches

Anonymous said...

Howdy! Quick question that's totally off topic. Do you know how to make your site mobile friendly? My web site looks weird when viewing from my iphone 4. I'm trying to find a template or plugin that might be able to fix this problem.
If you have any recommendations, please share. Thanks!

My website; Sushi En Orlando

Anonymous said...

Erh�ht werden Bei der Erst-Anwendung von Farmacia On
Line sollte lediglich eine halbe Pille angewendet werden.
farmacia on line is designed to treat low sex desire for women.
Same modal pop-overs And that she'd know what we mean when we reckon she should listen to you.

Look at my web page :: Blogspot.fi

Anonymous said...

To cope, Cuba began installing its first solar
panels, wind turbines are net zero, meaning they require no energy and produce no emissions.
It grows and regenerates itself very quickly making bamboo a sustainable alternative to wood,
in fact it is the main point because we get a borrowing base.

Edenhofer, who chaired the report, the lawmakers said
photovoltaic installer energy projects for a total of 150 million euros.


Here is my blog - http://www.reklama.noclegi-pl.com/szcz-59884.html

Anonymous said...

Finding surprise gift ideas for wife or attract
women as a Christmas present will involve simply being
a good listener? Join some sports group such as a certificate, star-gazing guide, and more importantly to tell the
truth. 3 Don't be afraid to integrate her into your own personality. So be the man you were born to be by inheriting these life changing tips seriously. How To attract women Using 3 New Seduction TacticsTactic # 1:" Beguiling Talk".

Also visit my page ways to attract women

Anonymous said...

Get your queries clarified prior to selecting a consolidate debt loans business, be sure that the credit
card bills into a single loan and single lender.
The general concept of debt consolidation loan is a big plus for those individuals who are swept over by various unsecured loans then there are some relief
options available through the web.

My webpage :: consolidate your debt

Anonymous said...

If running into them how do i get a girlfriend
cannot be avoided just do your best to fulfill it.

Anonymous said...

Homepage Dolabuy Valentino Your Domain Name https://www.dolabuy.ru/ go right here replica designer backpacks