Subtle mistake I made with Data Binding

I ran into a problem on RunPee.com where some text data wasn’t being displayed in a TextArea that was using data binding. It took me a while no nail down the bug because of the subtlety of the error I made. So I thought I’d share.

Suppose I have a variable declared as such:

[Bindable] private var myText:String;

And I have a TextArea like this:

<TextArea id="myTextArea" text="{ myText }" />

Pretty simple. Anytime I change the value of myText it will be updated in the TextArea. Ahh, the beauty of data binding.

The error I made was that under certain cases I directly changed the text value of myTextArea as such:

myTextArea.text = "";

Now in these cases the property myText hasn’t changed – which was the mistake I made.

The problem occurs when the user browses back to the same movie that they were at originally. In that case myText is “changed” but to the same value it had before. In that case data binding never fires and the text displayed in myTextArea doesn’t update. It stays as an empty string and not the value of myText.

This is really just a problem of poor programming. I should never had directly changed the value of myTextArea.text. Instead I should have said:

myText = "";

That would have “zeroed” out the text in myTextArea just as I wanted to and then when the user browsed back to the same movie the value would change again thus updating myTextArea is needed.

But as we all know code grows organically over the span of a project and sometimes what we wrote last week doesn’t jive with what we wrote today. That’s how this bug was introduced.

The easiest way to avoid this bug is to not give the TextArea an id. That way you can’t change it’s text value directly and must always rely on data binding. That works in instances where you never need to talk to the component for any other reasons. If you have to, say, move the TextArea around then you’ll have to give it an id. In that case just be careful.