Swiz example application with Presentation Model pattern
About a month ago I was introduced to the Swiz application framework for Flex. Within an hour or so, I was not only sold on the simplicity and effectiveness of the framework, I was digging around in the source adding features. Shortly after that I started collaborating more closely with Chris Scott, creator of Swiz and a coworker of mine, and Sönke Rohde, the other Swiz team member. The three of us have been cranking away adding new features ever since and have a lot planned for the coming months.
Now that introductions are out of the way, let’s look at some code. I’m really not going to try and explain much of anything here because I’ve done that (heavily) in the code and comments of the application. In the recent past I have repeatedly found myself frustrated with a lack of examples when reading about new frameworks or projects people are promoting. I learn best and quickest when I can see something in action and figure out how it works, so I created this example for other people like me. If you have questions, comments or suggestions about the application you can obviously post them here, or you can post them in the Swiz Google Group where I will also be posting a link.
Lastly, a couple of disclaimers.
- Only the Employees view of the application contains anything. I only created multiple tabs to facilitate the mode monitor at the bottom of the app.
- I’ve placed the ASDocs above the metadata tags for the sake of readability and simplicity. In a real application the ASDocs (unfortunately) go between the metadata and the code.
You can leave a response, or trackback from your own site.

Great example. I’m using Presentation Model pattern with Swiz like this, and it’s being a breeze to develop my applications so far, and the neat features that swiz 0.6 have are even better!
Thanks a lot and keep up the good work
Awesome work Ben! Thank you greatly for putting this together!
Nice Sample.
But I’ve a problem when Swiz injects my members on my views like in your Employee-View. So i listen on the creationComplete-Event of my view and want to have at this moment access to the from swiz injected member. But at this time the member reference is null and not filled at this time. how can i handle this?
Thanks
Hi Ben,
this looks great! A.t.m. I’m investigating different frameworks and Swiz is very promising. I really like the use of metadata for mediation and that you guys use mxml for the IoC container. Im also looking at Spring actionscript and Parsley. every one has great features… difficult to choose
Swiz definately seems the most lean and mean, Spring actionscript has the most powerful Ioc container and supports changing the settings without recompiling which may come in handy with systems in production. But this comes with a price tag: No good ide support and you need to manually include classes that are used in the context. Parsley seems to be very complete, both schemes are supported, but have to investigate further.
Anyway, success with the further implementation! One thing i would focus on is a good example with modules. These days with so many frameworks it’s on if the first questions many people ask. Looks great, but how does it handle modules (and module / shell communication)?
cheers, Arnoud
@ArgV – As it stands now, Swiz does its injections in response to the ADDED_TO_STAGE event, which happens after CREATION_COMPLETE. The next feature I will be working on is making the injection event configurable, so you will be able to make Swiz inject values earlier if you so choose. In the meantime, if you implement IInitializingBean, Swiz will call initialize once the injections have been made, allowing you to utilize those values.
@Arnoud – Thanks. I/we agree module support is very important and an official workflow is coming. Keep an eye on the Google Group and elsewhere for announcement of when that is finalized.
Thanks for the example…
I got two questions…
1… By looking at your mvc structure… where you would put custom classes?… This might be not that swiz specific… but I got issues in general to get my head around the question where to put custom classes within my MVC structure… sometimes when the app you are working on gets very graphical you need a lot of custom classes to deal with the view… and example would be an media player… buttons / states / animations and so on… now by bringing in another element like the presentation model the whole thing looks even harder understandable to me…
2 Regarding the use of these two interfaces within your app. Was it more the sake of an example? or why have you used interfaces in this particular case…. To me it doesn’t seem clear … Do you use interfaces for the presentation model in general ?
Thanks for helping me out with that
Ben, major props for this app. I’ve spent the last hour going through it, and your use of ideal architectural conventions with not only Swiz, but the Presentation Model pattern is pristine and right on the money. This app truly demonstrates how flexible (no pun intended) that Swiz is and how it can be used in tandem with additional architectural design patterns. Most importantly, the example is simple, which maintains consistency with the Swiz framework objective and accurately represents the vision – to provide absolute simplicity for complex applications… which is the entire idea behind design patterns and micro-architectures in the first place. Yet, this truth has gotten so convoluted that we often see design patterns and micro-architectures adding another level of complexity… the exact opposite of what they’re intended for. Case in point, it is great to be working with people that understand this.
Bigups!
-DanO
I like your example yet I feel like for the beginner with both flex and swiz (like myself) I get lost in the presentation model and flow of the app. It looks as though you dispatch all events through the presentation model and then a global application controller handles them. How would you do this differently (or not) if say you had more ui elements and non application wide shared functionality in your employee view and needed an employee view controller to update the model and view appropriately. Would you inject the employeeviewcontroller into the view at this point or would you pass an event from the presentation model to the controller and then update the model there (in which case does the view automagically get updated when the model does)…and of course why
?
Also I’ve been trying to figure out how to update the “currentState” of my views that have multiple states using this same type of architecture but the only solutions I’ve come up with are to listen for a custom StateChange event in my view and update the currentState property in the mxml or pass the view to the presentation model and update it there…any ideas? It looks like instead of using states you just set the visible property on the form… Thanks for any clarifications you can bring to beginners!
Hi Mike,
First, I should point out that if you are new to Flex, you might want to delay jumping into frameworks (even Swiz) and design patterns like presentation model. Its usually a better approach to learn and get comfortable with the Flex framework and what it provides by itself before getting into deeper topics. That way you better understand the problems the advanced topics are aiming to solve.
That being said, the presentation model is simply one option for designing an application, whether it uses Swiz or not. If you are not using PM you would generally just mediate events in your controller that are dispatched directly by views, or you could inject controllers into your views. The appropriate solution really depends on your app and its needs. Swiz does support a view attribute in the [Mediate] tag, which allows you to specify that a controller should only mediate events of the given type if they come from a view of the given type.
It’s no secret I hate Flex states.
I have never encountered a situation where I felt a state would solve my problem better than a visible toggle or addChild/removeChild would. The truth though, is that whether you use states or some other mechanism you generally will want to bind to a property on your model, so you can control your view in a meaningful way. Your controller or model should be setting properties like isEditing that your views bind to, not myView.visible = false.
Hope that helps,
Ben
[...] this post I have simply converted the Swiz example application I created using the Presentation Model pattern. The conversion took maybe 30 minutes, which [...]
Hi and thanks for the example. I really love Swiz.
Is there any reason why you prefer using the method ‘setSelectedEmployee’ rather than the setter of the selectedEmployee in the IEmployeeViewPresentationModel and so the EmployeeViewPresentationModel.
Thanks in advance.
I have just gotten in the habit of creating explicit setter methods so that the property is technically read only. Since the setter is public as well there is nothing stopping classes from using it, but it conveys intent a bit better I think. Definitely just a matter of preference and something you can choose to implement or not.
Hey Ben
Great example first of all, and thanks for posting it. I have been meaning to separate my logic from my views for a while now, and this seems like a perfect way to do it.
In regards to your example, under the IEmployeeViewPresentationModel
You have:
[Bindable( event="employeesChanged" )]
function get employees():ArrayCollection;
How would employeesChanged get dispatched? I did a search and couldn’t find what calls this event…
Basically what I am trying to have happen is if I have a delegate that goes out, gets some data and lets say it updates the employees under the ApplicationModel, how would
a) IEmployeeViewPresentationModel find out about it
b) How do activate a particular function within the view EmployeeView when this model is changed?
I hope those 2 questions make sense,…and any help would be appreciated.
Thanks
Nice example Ben – really appreciate all the comments in your code.
Frank – the employeesChanged event is dispatched by the implicit setter in EmployeeViewPresentationModel.
Frank – actually I’m wrong it is not an implicit setter.
The event is dispatched by clicking in the datagrid in EmployeeView
itemClick=”{ model.setSelectedEmployee( dg.selectedItem ) }”
I have a question regarding using Swiz with Presentation Model pattern.
Usually the saveUser() dynamic mediator would receive some kind of save confirmation from the server after it has been carried out.
If the view is to give feedback to the user by, for example, pop up an alert with “Saved” title and text “Successfully saved user XXX”, what would the recommended way of doing this?
1. By using [Autowire(view=true)] – is this even relevant when using presentation models?
2. Using Swiz.dispatchEvent() to dispatch a custom AlertEvent with title and text properties event and have the presentation model listen to it.
–Swiz.dispatchEvent(new AlertEvent(AlertEvent.ALERT, title, text))
3. By adding a callback property in the UserEvent that is called by the mediator.
–event.callBack(title, text)
4. By directly calling a method on the presentation model in the mediator by autowiring the presentation model into the controller.
presentationModel.alert(title, text);
5. Have a setter in the presentation model and set it in the controller with an AlertVO containing title and text properties.
6. Have the ‘alert’ setter in the domain model.
James, entries from first time commenters are held for moderation. I had 7 different ones from you. Not sure why you kept submitting before you were done, but I have combined them into a single entry.
To answer your question, there are a few different ways you can accomplish this. You mention a mediator in your comments but I don’t generally use mediators. Mediators are more or less an alternative to presentation models, so the two usually aren’t used together. My preference would probably be close to your #2, with the main difference being the controller using an injected dispatcher. In fact, in Swiz 1.0 there will be no static methods on Swiz, so that will be the only way.
Hope that helps,
Ben
Thanks for that Ben. What do you think about actually having the result and fault handlers in the presentation models?
By the way, the mediators I mentioned in the previous post were the Swiz dynamic mediators in the controller.
The 7 part comment was so I could figure out which part of my long comment this comment system didn’t like and wouldn’t let me post
It just took me to a blank screen after I submitted so I kept halving my post until I reproduced the problem.
In the end, I narrowed it down to a code snippet but it seemed to post fine by itself… weird.
I don’t think presentation models are an appropriate place for service handlers. Generally speaking, they should be completely unaware of their surroundings.
[...] pose much of an issue (although there would still be better places to put this code, such as in the presentation model if you are using [...]
Hey Ben,
I was thinking about your reply to James’s comment above and it raised a question …
PresentationModels seem to take the place of controllers in MVP so I’ve been essentially viewing them as alternatives to controllers (I know they differ, but for the most part that’s how I’ve been thinking of them) .
However, looking at the Swiz ServiceLayer example (http://bit.ly/9jzlZQ) it is the controller which possesses the IResponder’s result/fault handlers.
If PMs are basically alternatives to Controllers, and these handlers don’t belong in PMs (I agree, that seems wrong) do you have a recommended setup that works well in practise?
Thanks,
Neil
Hey Neil,
I’ve not researched MVP much at all, so am not 100% sure how it differs from MVC and PM. I don’t see PMs as alternatives to Controllers at all. I view PMs as more of a model adapter, whose purpose is to serve one or more views and present data to them, and provide an API to them in a semantically meaningful way.
So, a PM might expose a method called getContacts(), but behind the scenes it dispatches an event that is handled by a controller, or calls a method directly on a controller, and the controller in turn calls a service. When the service returns the controller (or a command, if you prefer) sets data on a model. One or more presentation models are generally bound to these larger, more general models in order to populate their local, semantically meaningful properties.
That was a mouthful, but hopefully it makes sense. I am starting to think maybe I should write a post about my approach to presentation models, since it seems to be a fairly common topic lately. Perhaps I will.
Ben
Thanks, I think that makes sense (but I agree, an elaborated example/post would be a great idea given the interest).
“mvp” – oops, that’s me displaying my ignorance. I made an assumption that presenter = presentation model. Okay, so knowing that it’s meant to be mvc + pm clears things up a little.
If I do understand you properly: the PM would have a reference to both a controller/command and the main model (or at least properties of the main model), and the controller/command would have a reference to the main model (or properties of it). The PM would update the model unless external data was required, in which case the controller /command would get the data and update the model.
If that’s not right let me know, else thanks very much for providing some clarification
That is correct, Neil. My only addendum to that is I usually just have the PM dispatch an event (using Swiz’s system dispatcher) rather than having the PM directly reference the controller or command. Some people don’t like that though and do it exactly as you said. I think either way is fine, and its just a matter of personal preference.
[...] for a few handy pointers and putting up with my questions. Also, thanks to David Tucker, Ben Clinkenbeard, Brian Kotek, and Richard Lord for instruction and [...]
[...] b) http://www.benclinkinbeard.com/2009/05/swiz-example-application-with-presentation-model-pattern/ Ben Clinkinbeard's example. [...]
When I import that project into Flash Builder 4 using the SDK3.5 I get :
Description Resource Path Location Type
Design mode: Cannot load swiz-0.6.1.b2.swc (reason: ERROR: Load Verify). It may require classes (such as Adobe AIR components) that are not supported by design mode. Check the Eclipse error log for more details. SwizUserAdmin.mxml /SwizUserAdmin/src Unknown Problem
When I create a news Project import SWIZ RC1 using SDK4.1 I get similar SDK errors.
How to use SWIZ with Flash Builder 4?
Hi Ben,
Thanks for the example and source code. However, it looks like the sample source code is still written for swiz-0.6.1, which is not available for download on swiz web site.
It would be good if there are zip archive of the sample code for each never version of the swiz release, especially the most current one, 1.0-RC1.
Regards,
Hi Ben, in the new Swiz documentation is this Presentation Model explained without the interfaces. Is there any purpose, you have been using this interfaces? I mean, I can imagine you could create different Presentation-Models with different implementations or maybe for Unit-Tests.
Thanks for your comments.
roberto