Saturday, 21 February 2009

Named Bindable and PropertyChangeEvent

I had an issue with using named bindables today and could not figure out why it wasn't working. I was using a PropertyChangeEvent as I not only wanted to bind to the property but also listen to the event and remove the previous value from an array (using the oldValue property of the event).
This worked:
private var _boundProperty : String;

[Bindable( "namedBindable" )]
public function get boundProperty() : String
{
return _boundProperty;
}

public function set boundProperty( value : String ) : void
{
_boundProperty = value;

dispatchEvent( new Event( "namedBindable" ) );
}
But this didn't:
private var _boundProperty : String;

[Bindable( "namedBindable" )]
public function get boundProperty() : String
{
return _boundProperty;
}

public function set boundProperty( value : String ) : void
{
_boundProperty = value;

dispatchEvent( new PropertyChangeEvent( "namedBindable" ) );
}
It turns out that if you use PropertyChangeEvent Flex is a bit picky and doesn't use it for binding unless you populate the property property! 
Like this:
private var _boundProperty : String;

[Bindable( "namedBindable" )]
public function get boundProperty() : String
{
return _boundProperty;
}

public function set boundProperty( value : String ) : void
{
_boundProperty = value;

dispatchEvent(
new PropertyChangeEvent(
"namedBindable",
false, false,
PropertyChangeEventKind.UPDATE,
"boundProperty"
) );
}
This seems a bit odd to me as just a plain event works fine with no additional properties. Anyway, hopefully this blog post will stop anyone else wasting time investigating this problem.

2 comments:

  1. God, thanks for this entry this confused the hell out of me

    ReplyDelete
  2. No problem. It was a very annoying problem to debug so I hope I managed to save someone else the pain!

    ReplyDelete