Thursday, March 12, 2009

Issues with event bubbling in Flex

These days, I came up with a pretty obscure situation, which took me two hours of useless browsing, and an icq session with a colleague of mine to solve. The solution (at least, its implementation) was far simpler than I expected. So, here is the situation:

In the main application's MXML markup, I declared a FormComponent (a custom component that extends Form). The FormComponent declares a FormController, which is an AS 3 class that deals with the data management, and some other features of the form. At some point, the FormController dispatches a custom event that is supposed to be caught by the FormComponent . In this way, when I declare the FormComponent in the main application, I could assign a handler for this event without even knowing who dispatched it. This happens because of the principle of event bubbling, i.e when an event is dispatched, it goes up the object tree (the MXML hierarchy, respectively) until it is caught by a listener.

Unfortunately, in this case, event bubbling would not happen (i.e, nothing will really work) unless some changes were done to the AS 3 class. The reason for this is that event bubbling pretty much happens when we use visual objects (trees, comboboxes, lists, etc). In order to make my FormController class applicable I had to make it implement an interface called IMXMLObject. This interface requres only one method to be implamented - initialized. This method would work instead of a class constructor (we don't have to provide a constructor - anything has to be declared in the initialized method. The syntax of the initialized method is as follows:

initialized(document:Object, id:String):void

In simpler words, when my FormController is initialized, it would be provided with these two arguments. the id is clear enough, any MXML object has an id, regardless of whether we declare it or not. What is more interesting is the document. I haven't had the time to go deeper in that, but it turns out that the document provides a reference to the MXML document that created the object. what I had to do in this initialized method is simply to assign a reference to the document parameter in a local variable - _document.

now, when I needed an event to be dispatched, rather than doing this:
this.dispatchEvent(....)
I had to do it this way :
_doucment.dispatchEvent(...)

... and it worked perfectly

No comments: