Thursday, March 29, 2007

Wizard Binding (binding things up that don't want to be bound)

Flex Data binding ROCKS. Doesn't it? The concept and execution is AS is pretty darn easy and very powerful. But binding things in MXML? Absolutely rocks. So fast and easy.

But it sure does suck when it doesn't work like ya thing you should.

I've been building a wizard lately. It seemed to me like it would work out awfully well if I could just bind certain properties to my "next" button based on the state the wizard is in. Once the user has made the correct decision (the item is no longer null, my list is no longer empty, etc) the next button would just light up and away we would go!

I bound them as one would expect using MXML but it just didn't work out for me.

The bindings just wouldn't execute at all. But I want bindings. I NEED bindings. So I decided to bind them "by hand". (Any time I have to do things a longer way than I feel I should it's always "by hand".)

I'm a big fan of code behind. Code just doesn't belong in MXML if we can help it. So for my wizard of course I have a code behind class. In that class I have a function that I use to change state (rather than just calling currentState="newState";). In this function I handle my next button bindings (and any other bindings that I need to happen when the state has changed and my new items need to be tied up). This is what it looks like:


private function navigateToState(newState:State):void
{
this.currentState = newState.name;
PopUpManager.centerPopUp(this);

//reset next button
nextButton.enabled = true;
if(nextWatcher)
{
nextWatcher.unwatch();
nextWatcher = null;
}

if(currentState == "albumSelection")
{
nextWatcher = BindingUtils.bindProperty(nextButton, "enabled", this, "selectedAlbum");
BindingUtils.bindProperty(this, "selectedAlbum", albumSelector, "selectedAlbum");
}

if(currentState == "imageSelection")
{
nextWatcher = BindingUtils.bindProperty(nextButton, "enabled", fileList, "length");
}
}

By the way, nextWatcher is a class variable of type ChangeWatcher. This is returned from a binding and can use it to control an existing (or create a new) binding. It's a rather powerful class and I definitely plan to talk some more about it later!

Please if anyone else has ANY ideas on how I can do this with MXML then I'm all ears. I do really love shortcuts. Lazy programmers make good programmers right?

-Jason Crist

No comments: