Flex Lazy Binding - apache-flex

Inspired by the lazy loading abilities of Hibernate I wanted to make the model part of my Flex UI request data from the server only when necessary. I thought this would be as simple as adding a public accessor that only sends server requests when the variable is accessed.
public function get tab2AC():ArrayCollection
{
if(_tab2AC == null){
//Request data from server
}
return _tab2AC;
}
Problem is that Flex seems to access all bound variables on application launch, even if the referencing component has yet to be created. So even though the DataGrid with dataProvider="{tab2AC}" has yet to be created, the server request still goes out, thus defeating the "only when required" laziness.
I do not want to place the server request inside a creationComplete handler as I want to keep my UI model ignorant of view state and my view ignorant of server requests.
Interestingly, if I add an Alert.show("anything"); inside the accessor, it works as desired.
UPDATE: Here is a full example. Set breakpoints and you'll see that Flex accesses both variables even though titleForScreen2 is not used by any created component.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
private var _titleForScreen1:String;
private var _titleForScreen2:String;
public function get titleForScreen1():String {
if(_titleForScreen1 == null){
//Server Request
}
return _titleForScreen1;
}
public function get titleForScreen2():String {
if(_titleForScreen2 == null){
//Server Request
}
return _titleForScreen2;
}
]]>
</fx:Script>
<mx:ViewStack>
<s:NavigatorContent label="Screen 1">
<s:Label text="{titleForScreen1}"/>
</s:NavigatorContent>
<s:NavigatorContent label="Screen 2">
<s:Label text="{titleForScreen2}"/>
</s:NavigatorContent>
</mx:ViewStack>
</s:Application>

Bindings in flex are pretty stupid. More of a proof of concept than an actual optimized production quality feature. What's worse is that short of modifying the compiler, there's little you can do about it without having all sorts of verification logic in your getter or (perhaps more likely) some kind of interceptive layer that makes sure that expensive calls are only made when the UI state is meaningful. At that point however, you might as well do away with bindings altogether and just implement an active controller for a passive view.
I know this is a pretty lame answer, but it's true. I've been a flex developer for several years and have had a complicated relationship with its binding feature for just as long. As well, over all this time, the only thing that has changed in the binding implementation is the ability to do two-way bindings.
By the way, syntactically I'd use a regular method rather than a property for returning a promise. Properties are often read as synchronous and cheap(-ish) operations, whereas a method (especially one that returns a promise) would have more flexible connotations.

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
private var _titleForScreen1:String;
private var _titleForScreen2:String;
public function get titleForScreen1():String {
if(_titleForScreen1 == null){
//Server Request
}
return _titleForScreen1;
}
public function get titleForScreen2():String {
Alert.show("test");
if(_titleForScreen2 == null){
//Server Request
}
return _titleForScreen2;
}
]]>
</fx:Script>
<mx:ViewStack>
<s:NavigatorContent label="Screen 1">
<s:Label text="{titleForScreen1}"/>
</s:NavigatorContent>
<s:NavigatorContent label="Screen 2">
<s:Label text="{titleForScreen2}"/>
</s:NavigatorContent>
</mx:ViewStack>
</s:WindowedApplication>
Breakpoints on lines 12 and 19, check out the stack trace during each, also you can pop open Binding and take a look at wrapFunctionCall (drop a breakpoint in there too). So when it gets to lines 12 and 19, it hits them 2 times because of the preloader dispatching a complete event. I put breakpoints in every file that the stack-trace showed the execution path moving through. Unfortunately I couldn't find the point where it caused 2 calls to happen (must be in the parts I don't have the source for) it seemed every spot in the trace was only called once but I think the wrapFunctionCall was called twice during the period of those two executions. The third one that happens is due to a call to doPhasedInstantation which calls down to execute on Bindings for all the children that have the systemManager, so it would seem somehow the components have a system manager even though they may have not yet been added to the stage or created. Sorry I don't have a more concrete answer for why each of these has to happen but my guess is there's some good reason.
Ah yah almost forgot, also you'll see when the Alert is shown it causes an error but that error is captured in the wrappedFuncitonCall method in Binding.as
catch(error:Error)
{
// Certain errors are normal when executing a srcFunc or destFunc,
// so we swallow them:
// Error #1006: Call attempted on an object that is not a function.
// Error #1009: null has no properties.
// Error #1010: undefined has no properties.
// Error #1055: - has no properties.
// Error #1069: Property - not found on - and there is no default value
// We allow any other errors to be thrown.
if ((error.errorID != 1006) &&
(error.errorID != 1009) &&
(error.errorID != 1010) &&
(error.errorID != 1055) &&
(error.errorID != 1069))
{
throw error;
}
else
{
if (BindingManager.debugDestinationStrings[destString])
{
trace("Binding: destString = " + destString + ", error = " + error);
}
}
}

Your statement is not true, tab2AC getter is not accessed by Flex app on launch, as a proof here is the full application code:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
private var _tab2AC:ArrayCollection;
public function set tab2AC(value:ArrayCollection):void
{
_tab2AC = value;
}
[Bindable]
public function get tab2AC():ArrayCollection
{
if(_tab2AC == null){
trace("THIS WILL NOT BE CALLED");
}
return _tab2AC;
}
]]>
</fx:Script>
</s:Application>
As you can see, the trace will not be triggered, so your problem seems to be coming from a call to that getter from somewhere in your app, to find it, put a break-point and then "Step return" when needed.
That being said, you should not implement the lazy loading this way directly in the getter as the service call is asynchronous.

Why not return back a new ArrayCollection when the variable is null, then set the source on the ArrayCollection when the server call returns?

I think this is just wonky behavior of the debugger, rather than what would happen in ordinary execution. If you put any logic in there that will enable you to determine that the function was called that doesn't tie into the debugger (such as setting the text on a label), then the getter doesn't get called. However, if you put a trace statement in there, the getter does get called.
The conundrum is how much do you want to depend on the idea that this is only going to happen in debugging, and how critical is it to get the real behavior while you are using the debug player?

So yeah, that's just the way it is. Since Flex evaluates bindings immediately, I have to delay bindings until creation in order to prevent premature evaluation. Seems like extra work to undo Flex's weird behavior, but that's just how it goes sometimes.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Script>
<![CDATA[
import mx.binding.utils.BindingUtils;
import mx.binding.utils.ChangeWatcher;
private var _titleForScreen1:String;
private var _titleForScreen2:String;
public function get titleForScreen1():String {
if(_titleForScreen1 == null){
//Server Request
}
return _titleForScreen1;
}
public function get titleForScreen2():String {
if(_titleForScreen2 == null){
//Server Request
}
return _titleForScreen2;
}
public function updateLabel1(value:String):void {screen1Label.text = value;}
public function updateLabel2(value:String):void {screen2Label.text = value;}
public function bindLabel1():void {
var changeWatcher:ChangeWatcher = BindingUtils.bindSetter(updateLabel1,this, "titleForScreen1");
}
public function bindLabel2():void {
var changeWatcher:ChangeWatcher = BindingUtils.bindSetter(updateLabel2,this, "titleForScreen2");
}
]]>
</fx:Script>
<mx:ViewStack>
<s:NavigatorContent label="Screen 1">
<s:Label id="screen1Label" creationComplete="bindLabel1()"/>
</s:NavigatorContent>
<s:NavigatorContent label="Screen 2">
<s:Label id="screen2Label" creationComplete="bindLabel2()"/>
</s:NavigatorContent>
</s:NavigatorContent>
</mx:ViewStack>
</s:Application>

Related

Flex Spark RadioButton Deselected Event?

Is there a way to listen for this? I can easily listen for click which selects a RadioButton, but I can't seem to find a way to listen for when the RadioButton has been deselected.
Any ideas?
Thanks!
Back in the Flex 2 days, the "change" event triggered when a radio button was deselected. However, this little convenience disappeared in Flex 3, for some reason, and I don't believe that we were provided with any sort of replacement event.
Handling your events at the RadioButtonGroup level is all fine and well, except that there are times when you really want to handle the events on the radio button level -- particularly if you were hoping to interact with a data provider entry via an itemRenderer that is drawing the radio button.
Conveniently, I have a little bit of boilerplate code you can use as drop-in replacements for RadioButton and RadioButtonGroup that provide a "unselect" event at the radio button level. Here is the SmartRadioButton, first of all:
<?xml version="1.0" encoding="utf-8"?>
<s:RadioButton xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import events.SmartRadioButtonEvent;
public function notifyDeselect():void {
dispatchEvent(new SmartRadioButtonEvent('deselect'));
}
]]>
</fx:Script>
<fx:Metadata>
[Event(name="deselect", type="events.SmartRadioButtonEvent")]
</fx:Metadata>
</s:RadioButton>
And here is the SmartRadioButtonGroup:
<?xml version="1.0" encoding="utf-8"?>
<s:RadioButtonGroup xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
change="selectionChanged();"
>
<fx:Script>
<![CDATA[
import spark.components.RadioButton;
import components.SmartRadioButton;
protected var oldSelection:SmartRadioButton = null;
// Notify our old selection that it has been deselected, and update
// the reference to the new selection.
public function selectionChanged():void {
var newSelection:SmartRadioButton = this.selection as SmartRadioButton;
if (oldSelection == newSelection) return;
if (oldSelection != null) {
oldSelection.notifyDeselect();
}
oldSelection = newSelection;
}
// Override some properties to make sure that we update oldSelection correctly,
// in the event of a programmatic selection change.
override public function set selectedValue(value:Object):void {
super.selectedValue = value;
oldSelection = super.selection as SmartRadioButton;
}
override public function set selection(value:RadioButton):void {
super.selection = value;
oldSelection = super.selection as SmartRadioButton;
}
]]>
</fx:Script>
</s:RadioButtonGroup>
The two property overrides are in there to make sure that we correctly update the oldSelection, in the event of a programmatic change to the group's selection.
SmartRadioButtonEvent isn't anything fancy or important. It could probably just be a plain Event, since there isn't a special payload.
I have tested the above code, and it all works, but there are surely edge conditions, and other oddities that should be addressed, if it's used in a larger system.

UIComponent in a test case is null

I have this App.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:Button id="bt" label="click me"/>
</s:Application>
And this test case:
package flexUnitTests
{
import flexunit.framework.Assert;
public class AppTest
{
[Test]
public function testApp():void
{
var app:App = new App();
Assert.assertNotNull(app.bt);
}
}
}
But app.bt is null. I want to access the button :(
Short Answer:
The life cycle methods have not run on app; so no createChildren() method was executed in order to create the child component of bt.
Longer Answer:
Things get slightly more complicated with the main application file, as it there is no higher level Flex component in the display hierarchy. I'm unclear on all specifics, but..
I think the Flex Compiler does some magic to set up this component--and the Flex Framework--that help makes the whole app work. You are, in essence, bypassing that work by creating your own instance of the component.

Handling mouse click in Flex 4 List to find the selected item (since itemClick is gone)

I have prepared a simplified test case for my question. It will run instantly in your Flash Builder if you put the 2 files below into a project.
I'm trying to display a List of strings and a confirmation checkbox in a popup:
In the real application I dispatch a custom event with the string selected in the list, but in the test code below I just call trace(str);
My problem: if I use click event, then the window closes, even if I click at a scrollbar (the !str check below doesn't help, when an item had been selected in previous use). And if I use change event, then the window doesn't close, when I click on the same item as the last time. And the itemClick event seems not to be present in spark.components.List anymore.
Any suggestions please on how to handle this probably frequent problem?
Writing a custom item renderer and having a click event handler for each item seems to be overkill for this case, because I have strings in the list.
Test.mxml: (please click myBtn few times - to see my problems with click and change)
<?xml version="1.0" encoding="utf-8"?>
<s:Application
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="400" minHeight="300">
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
private var _popup:Popup = new Popup();
private function showPopup(event:MouseEvent):void {
PopUpManager.addPopUp(_popup, this, true);
PopUpManager.centerPopUp(_popup);
}
]]>
</fx:Script>
<s:Button id="myBtn" right="5" bottom="5"
label="Open window" click="showPopup(event)" />
</s:Application>
Popup.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="240" height="240"
creationComplete="init(event)"
close="close()">
<fx:Script>
<![CDATA[
import mx.collections.ArrayList;
import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.events.CloseEvent;
import mx.events.ItemClickEvent;
import mx.managers.PopUpManager;
private var myData:ArrayList = new ArrayList();
private function init(event:FlexEvent):void {
// XXX in the real app data is updated from server
myData.removeAll();
for (var i:uint = 1; i <= 10; i++)
myData.addItem('Item #' + i);
}
public function close(event:TimerEvent=null):void {
PopUpManager.removePopUp(this);
}
private function handleClick(event:MouseEvent):void {
var str:String = myList.selectedItem as String;
if (!str)
return;
if (myBox.selected) {
Alert.show(
'Select ' + str + '?',
null,
mx.controls.Alert.YES | mx.controls.Alert.NO,
null,
handleConfirm,
null,
mx.controls.Alert.NO
);
} else {
sendEvent();
}
}
private function handleConfirm(event:CloseEvent):void {
if (event.detail == mx.controls.Alert.YES)
sendEvent();
}
private function sendEvent():void {
close();
// XXX in the real app dispatchEvent() is called
trace('selected: ' + (myList.selectedItem as String));
}
]]>
</fx:Script>
<s:VGroup paddingLeft="20" paddingTop="20"
paddingRight="20" paddingBottom="20" gap="20"
width="100%" height="100%">
<s:List id="myList" dataProvider="{myData}"
click="handleClick(event)"
width="100%" height="100%" fontSize="24" />
<s:CheckBox id="myBox" label="Confirm" />
</s:VGroup>
</s:TitleWindow>
Also I wonder, why do I get the warning above:
Data binding will not be able to detect assignments to "myData".
The Spark List dispatches an 'IndexChangeEvent.CHANGE'. You can listen for this event to know when the selection in the List has changed.
<s:List id="myList" dataProvider="{myData}"
change="handleIndexChange()"
width="100%" height="100%" fontSize="24" />
That event is only dispatched whenever the selected index actually changes, which means that when you reopen the window a second time an item might still be selected and when you click on that one, no CHANGE event will be fired. To fix this just deselect the selection before you close the window:
public function close():void {
myList.selectedIndex = -1;
PopUpManager.removePopUp(this);
}
Also make sure to dispatch your event with the selected item before you close the window (and deselect it).
As for your question about the binding warning: you get that message because you didn't mark 'myData' to be bindable. To fix this just use the [Bindable] tag:
[Bindable]
private var myData:ArrayList = new ArrayList();
or skip the binding altogether if you don't need it and just assign the dataprovider to the list in ActionScript:
myList.dataProvider = myData;
I'd recommend two solutions if you absolutely wnat to display what item was selected. Otherwise, the solution provided by RIAStar would do the trick.
Listen to rendererAdd and rendererRemove events within your PopUp
As explained here, you can easily access to your list's renderers without interfering with its virtualLayout business.
Use a custom renderer
I know. But as long as you keep your code clean, itemRenderers won't blow up your application's memory. They're made to render huge amount of items without memory leaks.
In your Test.mxml, modify the codes like:
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
private var _popup:Popup;
private function showPopup(event:MouseEvent):void {
_popup = new Popup();
PopUpManager.addPopUp(_popup, this, true);
PopUpManager.centerPopUp(_popup);
}
]]>
</fx:Script>
And in your Popup.mxml, I am not sure why you have the TimerEvent in the close function.
Also the trace won't be shown, as you are calling the close() function immediately after the alert's YES button has been clicked..

Get variable from ItemRenderer to Main Application

I have a List with TextInput as item renderer. I want to get the value entered in the TextInput (form the TextInputItemRenderer) and pass it the main application to do some checks(upon tapping enter on the textInput -- see code below).
I know that we can do it thru dispatching event but I still don't understand how to pass a variable from the ItemRenderer to the main app.
Help Pls.
Thanks
<?xml version="1.0" encoding="utf-8"?>
<s:ItemRenderer xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
autoDrawBackground="true" xmlns:components="components.*" width="100%"
>
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<fx:Script>
<![CDATA[
override public function set data( value:Object ) : void {
super.data = value;
}
protected function myTextInput_enterHandler(event:FlexEvent):void
{
trace(myTextInput.text);
What Next??
}
]]>
</fx:Script>
<components:ClearableTextInput text="{data.label}" id="myTextInput" enter="myTextInput_enterHandler(event)"/>
</s:ItemRenderer>
i'm not sure if I got your question correctly but would this help?
http://www.ajibanda.blogspot.com/2011/02/changing-currentstate-of-main-and.html
Instead of trying to access from MainApp to itemRenderer, i think you can do backward. Follow one of two solutions below:
In itemRenderer, assign value you want to check later to a public global variable on the MainApp. The limitation is you then only enable to check it on MainApp, not any where esle (other itemRenderer, component, module etc.)
Use EvenBus to put the value to a global container. Create a static eventBus instance in AppUtils, for example. In itemRenderer, AppUtils.eventBus.dispatch() an event with the value attached to it each time the value changed. And then use AppUtils.eventBus again to addEventListener() to retrieve the value and check wherever you want. Google AS3Commons for EventBus.

Deployed flex applet not processing web service results

When I test my deployed app in a browser the popup window continues to be displayed even after it should be closed. Everything works as expected when debugged in Flash Builder 4.
Following is currently what's happening: the request is sent to my restful web service, which processes the request, (seemingly) the ResultEvent is called which in turn dispatches the profileEvt dynamic event that changes the view state. However, the popup window does not get closed and the applet gets 'stuck.'
Anyone know what could be the problem? Below are the flex applet web service event listeners/handlers:
webService.addEventListener(ResultEvent.RESULT, function(event:ResultEvent):void
{
var rawData:String = String(event.result);
var profileEvt:DynamicEvent = new DynamicEvent("profileSaved", true);
profileEvt.data = JSON.decode(rawData).profile;
dispatchEvent(profileEvt); // Dispatch profile saved event
_progressPopUp.closePopUp();
dispatchEvent(event); // Dispatch submit profile button clicked
});
webService.addEventListener(FaultEvent.FAULT, function(event:FaultEvent):void
{
Alert.show("Could not create profile; please try again later.\n" + event.message, "Status");
_progressPopUp.closePopUp();
});
var params:Object = {"profile" : profile};
try
{
_progressPopUp = PopUpManager.createPopUp(this, com.profs.ui.components.ProgressPopUp, true);
_progressPopUp.eventSource = webService; // Set source of progress events
webService.send(JSON.encode(params));
}
NOTE:
com.profs.ui.components.ProgressPopUp is a custom component; the code for it is below:
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" layout="absolute" width="300" height="200" showCloseButton="false" title="Status" creationComplete="init()">
<fx:Declarations></fx:Declarations>
<fx:Script>
<![CDATA[
import mx.managers.PopUpManager;
[Bindable] public var eventSource:Object;
private function init():void
{
PopUpManager.centerPopUp(this);
}
public function closePopUp():void
{
PopUpManager.removePopUp(this);
}
public function completionHandler(event:Event):void
{
closePopUp();
}
]]>
</fx:Script>
<mx:ProgressBar id="progressBar" indeterminate="true" mode="event" source="{eventSource}" complete="completionHandler(event)" verticalCenter="0" horizontalCenter="0"/>
</mx:TitleWindow>
I am not familiar with the com.profs.ui.components.progressPopUp component, but it is possible that the closePopUp() method has a bug in it. You could try to remove the ProgressPopUp directly using the PopUpManager method. For example instead of:
_progressPopUp.closePopUp();
try
PopUpManager.removePopUp(_progressPopUp);
I also don't know off the top of my head what the rules for closures are (i.e. at which point is the _progressPopUp variable copied into the ResultEvent.RESULT event handler. You could try moving that particular event handler below the line where you actually created the _progressPopUp instance.

Resources