Tuesday, June 10, 2008

Flex: Objects in Views

Imagine the following requirement:
The application needs a combo box that has the following options:
  • delete
  • mark as spam
  • bounce
When delete is selected the current email (the one being viewed) needs to be moved from the inbox to the trash.

When mark as spam is selected the current email should be tagged as spam.

When bounce is selected the server should send a reject message to the server where the email originated.
Assume you are using the web. The traditional approach is to create a drop down with unique values that can be used on the server side (generally as a case statement). The unique values are strings, which represent keys, which are used to determine what the correct course of action is. This scenario works, and is familiar to most web developers, but it's not the most elegant solution.

Flex offers you a better solution. The Flex ComboBox allows you to set the dataProvider to an array of anonymous objects which can contain pretty much whatever you need. Even if you don't know Flex and ActionScript, the following code should still be readable, and interesting.

function init() {
comboBox.dataProvider = [{label: "delete", command:DeleteCommand}, {label: "mark as spam", command:MarkAsSpamCommand}, {label: "bounce", command:BounceCommand}];
comboBox.addEventListener("change", function(){ new comboBox.selectedItem.command().execute(); });

function init() {
comboBox.dataProvider = [{label: "delete", execute:delete}, {label: "mark as spam", execute:markAsSpam}, {label: "bounce", execute:bounce}];
comboBox.addEventListener("change", function(){ comboBox.selectedItem.execute(); });

function delete() {
// delete implementation

function markAsSpam() {
// mark as spam implementation

function bounce() {
// bounce implementation

This is one of the things I really like about Flex. Since I'm not tied to HTML and strings, I can put whatever I like in the view. The first example keeps all the logic out of the view and simply creates a new command and executes it immediately. It's nice and clean without worrying about converting from strings to classes. The second solution relies on functions to handle processing. In this case you could be doing something as simple as showing or hiding components in the view (not something you'd need a class for).

Either way, I'm working with first class concepts, instead of string representations of first class concepts. The result is cleaner code that's easier to work with.
Post a Comment