Can somebody please explain this common binding pitfall to me? (using the wrong bindable event name) - apache-flex

I refer to this site link text
Using the wrong event name in the
[Bindable] tag can cause your
application to not bind your property,
and you will not even know why. When
you use the [Bindable] tag with a
custom name, the example below looks
like a good idea:
public static const EVENT_CHANGED_CONST:String = "eventChangedConst";
private var _number:Number = 0;
[Bindable(event=EVENT_CHANGED_CONST)]
public function get number():Number
{
return _number;
}
public function set number(value:Number) : void
{
_number = value;
dispatchEvent(new Event(EVENT_CHANGED_CONST));
}
The code above assigns a static
property to the event name, and then
uses the same assignment to dispatch
the event. However, when the value
changes, the binding does not appear
to work. The reason is that the event
name will be EVENT_CHANGED_CONST and
not the value of the variable.
The code should have been written as
follows:
public static const EVENT_CHANGED_CONST:String = "eventChangedConst";
private var _number:Number = 0;
[Bindable(event="eventChangedConst")]
public function get number():Number
{
return _number;
}
public function set number(value:Number) : void
{
_number = value;
dispatchEvent(new Event(EVENT_CHANGED_CONST));
}
I agree, the wrong example does look like a good idea and I would do it that way because I think it's the right way and avoids the possibility of a typing error. Why is the name of the constant used instead of it's value? Surely this can't be right?
I appreciate your insights

Because the standard Flex compiler isn't that clever at times... and I feel your pain! I've complained about this exact problem more than a few times.
If I remember correctly, it's because the compiler does multiple passes. One of the early passes changes the Metadata into AS code. At this point in the compiler it hasn't parsed the rest of the AS code, so its not capable of parsing Constants or references to static variables in other files.
The only thing I can suggest is sign up to the Adobe JIRA, vote for the bug, and hope that the compiler fixes in 4.5 bring some relief.

Related

Flex: getting the previous value of a combobox when it changes

I need to know the value from which a combo box is changing, when it changes. I've been all through the documentation for the events, and none of them let you know what the value is before user interaction changes it. (currentStateChanging is a total red herring!) Handling the open event and saving the value isn't a solution, because there are other ways to change the value.
I'm using the Flex 3.5 SDK.
Something like this?
var currentVal : Object;
private function onChange(newVal) : void {
// currentVal stores your previous value - do something with it
currentVal = newVal;
}
<mx:ComboBox change="onChange(event.target.selectedItem)"/>
I just used the "changing" event on a Spark ComboBox to solve this very problem but it's not available on the mx version
Also - see this
I've come to the conclusion that there isn't an answer :( The best workaround is to override all possible ways there are to set the value of a combo box, plus handle any events that involve the user changing the value, back up that value and then you have a trail of previous values. Then, put a lot of comments saying
this is a 3.5-necessary kluge! If doing this on another SDK you might have to change it!
=======
I've come up w/a solution, but it's not perfectly reliable (since it makes assumptions about how it will work in other SDKs) and its elegance is wanting:
<mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml" valueCommit="OnChangeAnyway()" change="OnChange()">
<mx:Metadata>
[Event(name='traceable_change', type="assets.LineComboChangeEvent")]
</mx:Metadata>
<mx:Script><![CDATA[
public static const CHANGE:String = 'traceable_change';
private var m_oOld:Object;
private var m_oNew:Object;
private var m_bCallLaterPending:Boolean = false; //This is necessary, because I found OnChangeAnyway() could be called any number of times before OnChange() is
private function OnChange():void {
var oNewEvent:LineComboChangeEvent = new LineComboChangeEvent(CHANGE, m_oOld); //there's nothing special in this class
dispatchEvent(oNewEvent);
}
private function OnChangeAnyway():void {
if (!m_bCallLaterPending) {
m_bCallLaterPending = true;
callLater(function ():void { m_bCallLaterPending = false;}, []); //presumably, whatever is passed to callLater() will be executed after everything else currently queued
m_oOld = m_oNew;
m_oNew = value;
}
}
]]></mx:Script>
m_oNew is obviously redundant because that value will be available to whatever handles traceable_change, but it does explain why I have to barrel-shift these objects.
There are a couple of reasons why I don't consider this reliable:
It assumes that the valueCommit handler will be called ahead of the change one. On my system, it always seems to, but I don't see that promise anywhere.
It assumes that whatever callLater() calls will be called after change is. See concerns for 1.

Data binding across multiple objects in Flex 3

I am new to Flex (got assigned to maintain an old project at work) and am having some trouble getting data binding to work correctly. I have a popup form class, AddOffer.mxml which uses a model AddOfferModel.as. On my popup form, I have the following component:
<mx:FormItem label="{getResource('addOffer.form.OFFER_DATE')}:"
labelWidth="90">
<views:OfferWindowDatesFragment
id="offerWindowField"
start="{model.offerStartDate}"
stop="{model.offerStopDate}" />
</mx:FormItem>
My AddForm.mxml file also has some embedded actionscript where I define my 'model' variable:
[Bindable]
public var model:AddOfferModel;
The model variables I am trying to bind to are standard getters/setters and look like this inside AddOfferModel.as:
[Bindable]
public function set offerStartDate(val:EditableInstant):void
{
_offerStartDate = val;
}
public function get offerStartDate():EditableInstant
{
return _offerStartDate;
}
private var _offerStartDate:EditableInstant;
[Bindable]
public function set offerStopDate(val:EditableInstant):void
{
_offerStopDate = val;
}
public function get offerStopDate():EditableInstant
{
return _offerStopDate;
}
private var _offerStopDate:EditableInstant;
Inside the OfferWindowDatesFragment component class, the start and stop variables look like this:
[Bindable]
public function set start(val:EditableInstant):void
{
_start = val;
}
public function get start():EditableInstant
{
return _start;
}
private var _start:EditableInstant;
[Bindable]
public function set stop(val:EditableInstant):void
{
_stop = val;
}
public function get stop():EditableInstant
{
return _stop;
}
private var _stop:EditableInstant;
Basically, I just want to bind the start and stop variables in my OfferWindowDatesFragment class to the offerStartDate and offerStopDate variables in the AddOfferModel.as file. Whenever I access the start/stop variables in functions inside the OfferWindowDatesFragment class, they are null.
I have an event listener function that gets triggered in OfferWindowDatesFragment anytime a user selects a new date, it looks like this:
private function changeOfferDate():void
{
start.currentValue = offerDateEditor.start;
stop.currentValue = offerDateEditor.stop;
}
Every time I reach this function, it throws up an error because 'start' and 'stop' are both null ... but should have been initialized and bound already. If I look at the variables in the debugger, I can confirm that values on the right side of the assignment expression are valid, and not what is causing the error.
I am not real familiar with how initialization works in Flex, and I assumed as long as I instantiated the component as seen in the first code snippet at the top of my post, it would initialize all the class variables, and setup the bindings. Am I missing something? Perhaps I am not properly initializing the model or class data for AddForm.mxml or AddFormModel.as, thereby binding null references to the start/stop fields in my OfferWindowDatesFragment class?
Any help would be greatly appreciated. Thanks!
EDIT:
I looked into this further and tried using Mate to inject the 'model' variable inside AddOffer.mxml with a valid AddOfferModel object:
<Injectors target="{AddOffer}" debug="{debug}">
<ObjectBuilder generator="{AddOfferModel}" constructorArguments="{scope.dispatcher}" cache="local"/>
<PropertyInjector targetKey="model" source="{lastReturn}" />
</Injectors>
I load the AddOffer.mxml dialog as the result of a button click event on another form. The function that pops it up looks like this:
public function addOffer():void
{
var addOfferDialog:AddOffer = new AddOffer();
addOfferDialog.addEventListener("addOffer", addOfferFromDialog);
modalUtil.popup(addOfferDialog);
}
It doesn't seem to be assigning anything to the 'model' variable in AddOffer.mxml. Does loading a view/dialog this way not trigger an injection from Mate by chance? (I realize this last part might belong in the Mate forums, but I'm hoping somebody here might have some insight on all of this).
In AddOffer.mxml, you have this code:
[Bindable]
public var model:AddOfferModel;
Is there something outside AddOffer.mxml that is setting this to a valid AddOfferModel? There should be. The nature of how the Flex component life cycle means that you can expect that things may be null at times as a View builds. So you should build your components to be able to "right themselves" after receiving bad data, if the data eventually comes good.
Data binding is one way to do this, but it may not paper over everything depending on what else is going on.
Have you verified that the model value you're getting is not null at the point where the user selects the date and that its offerStartDate and offerEndDate properties have been populated with valid EditableInstants? If both of those are correct, I'd start looking for pieces of the Views that expect to have stuff at a given instant and then don't recover if it is provided later.

{Bindable on function/ methods

Can we put [Bindable] on functions/methods? I know that bindable is used to change the value of the source property to destination property. But not sure if we can use that for methods. Can you guys give me reason why we cannot put/ if we can then what will be the outcome?
Can you guys give me reason why we cannot put/ if we can then what
will be the outcome?
You can use Bindable on get/set properties; which are implemented as methods. Sort of like this:
private var _myValue : Boolean;
[Bindable(event='myValueChanged']
public function get myValue():Boolean{
return _myValue;
}
public function set myValue(value:Boolean):void{
_myValue = value;
dispatchEvent(new Event('myValueChanged'));
}
[Disclaimer I wrote this code in the browser]
The purpose of Binding is to 'magically' link two properties together. So, when the source property changes, the destination property also changes.
How are you expecting to apply this concept to a function?

Passing along information on a FileReference Complete event

I need to pass along a string with my FileReference, or provide that string as an argument when an event fires. To be clear, it really annoys me that AS3 doesn't allow you to pass parameters on events.
Right now, I've extended the FileReference class to include an additional variable. I'm trying to get this to compile, but it won't compile; I think I don't know how to import this class correctly. If you can tell me how to import this class correctly so that I no longer get Error: Type was not found or was not a compile-time constant at compile time that would be great.
This is the extended FileReference class:
import flash.net.FileReference;
public class SxmFR extends FileReference {
public var housenum:String = "";
public function SxmFR(str:String) {
housenum = str;
super();
}
}
I've tried that in a .mxml and a .as in the same folder. Neither is automatically imported.
I've also tried to extend the Event class, but I couldn't figure out how to make the event dispatch, since I need to respond to the Event.COMPLETE event. If you can tell me how to make it dispatch on this, it also might work.
Please help me get this figured out, and much love and thanks to all involved. : )
If you add your event listener as a closure you have access to the variables in the current function:
function myFunction(): void {
var aParam: String = "This is a parameter";
dispatcher.addEventListener("eventName", function (e: Event): void {
// you can access aParam here
trace(aParam);
});
}
The aParam inside the function will have the same value as it had when addEventListener was called.

Flex: AMF and Enum Singletons – can they play well together?

I'm using Python+PyAMF to talk back and forth with Flex clients, but I've run into a problem with the psudo-Enum-Singletons I'm using:
class Type {
public static const EMPTY:Type = new Type("empty");
public static const FULL:Type = new Type("full");
...
}
When I'm using locally created instances, everything is peachy:
if (someInstance.type == Type.EMPTY) { /* do things */ }
But, if 'someInstance' has come from the Python code, it's instance of 'type' obviously won't be either Type.EMPTY or Type.FULL.
So, what's the best way to make my code work?
Is there some way I can control AMF's deserialization, so when it loads a remote Type, the correct transformation will be called? Or should I just bite the bullet and compare Types using something other than ==? Or could I somehow trick the == type cohesion into doing what I want?
Edit: Alternately, does Flex's remoting suite provide any hooks which run after an instance has been deserialized, so I could perform a conversion then?
Random thought: Maybe you could create a member function on Type that will return the canonical version that matches it?
Something like:
class Type {
public static const EMPTY:Type = new Type("empty");
public static const FULL:Type = new Type("full");
...
// I'm assuming this is where that string passed
// in to the constructor goes, and that it's unique.
private var _typeName:String;
public function get canonical():Type {
switch(this._typeName) {
case "empty": return EMPTY;
case "full": return FULL;
/*...*/
}
}
}
As long as you know which values come from python you would just convert them initially:
var fromPython:Type = /*...*/
var t:Type = fromPython.canonical;
then use t after that.
If you can't tell when things come from python and when they're from AS3 then it would get pretty messy, but if you have an isolation layer between the AS and python code you could just make sure you do the conversion there.
It's not as clean as if you could control the deserialization, but as long as you've got a good isolation layer it should work.

Resources