Flex Tip of the Day: validateNow() on text fields
(One in a series of random, daily, useful Flex tips.)
If you have a Label or another component that uses a Label or derives from a Label, you may run into situations where you need to update the Label’s text property and then immediately use its textWidth property in a calculation. Normally, the textWidth property will not be updated until later when the Label’s commitProperties() runs. But if you need to use its textWidth property immediately, you can call validateNow() on the Label. That will cause the Label’s commitProperties() to run immediately, after which you can get the correct value of textWidth.
In the example below, I’m using a Label to display the title of a document. When the underlying data structure changes, I need to update the title, then truncate its width to the width of the column it’s being displayed in. Here’s the commitProperties() of the UIComponent I’m using to do the display, which has a Label as a member variable:
override protected function commitProperties():void
{
super.commitProperties();
if (_documentListInfoChanged)
{
_label.text = _documentListInfo.title;
_label.validateNow();
_label.width = Math.min(_label.textWidth + UITextField.TEXT_WIDTH_PADDING*2, maxTitleWidth);
_documentListInfoChanged = false;
}
}
By the way, calling validateNow() can be useful in many situations; this is just one specific and common case.
Technorati Tags: Flex, Flex Tip of the Day




So if commitProperties calls validateNow which in turn calls commitProperties, does that not get into a recursive loop ?
(I havent tried it…thougjt its easier to ask)
BTW, your blog is one of the few truly useful blogs when it comes to Flex dev topics!
Sorry, I had a feeling this example was going to be confusing. I’m talking about two different objects’ commitProperties() methods. The example above is the commitProperties() method of my document item component, and the validateNow() ends up triggering the commitProperties() of the Label. So no, no recursive loop.
And thanks for the good word!
ah makes sense…on re-reading I realize you had made this clear. my bad.
Thank you SO much. I’ve been making crazy use of callLater to get around issues like this, but this solution is SOOOO much better.
Thanks! this was giving me a headache.
thanks. this was very helpful.
Thanks,
It helps me in very fine way
Thank you SO much. I’ve been making crazy use of callLater to get around issues like this, but this solution is SOOOO much better.
Thank you! ValidateNow is, indeed, applicable in many varying cases. Thanks for bringing this function to our attention.
The following methods don’t seem to work on Flex4 SDK Beta 2
label.validateNow();
label.invalidateSize();
However, I was able to get the width using TextLineMetrics:
label.regenerateStyleCache(false);
var textMetrics:TextLineMetrics = label.measureText( text );