set dataprovider in actionscript - apache-flex

I have a datagrid w/ dataProvider property set in MXML as:
dataProvider="{pagedResult.lastResult}"
How do I set the dataprovider in actionscript? I have:
protected function getResult (event:FlexEvent):void
{
pagedResult.token = mydata.paged();
adg1.dataProvider = pagedResult.lastResult;
}
but I'm doing something wrong as it does not work

Your code looks solid, I guess the issue is that you need to convert it. You didn't say what sort of data your service is returning, but for the purposes of this sample I'll assume an Array
Try something like this
var myCollection : ArrayCollection = new ArrayCollection(pagedResult.lastResult as Array);
adg1.dataProvider = myCollection;

First if you are going to set the dataProvider from Actionscript I would remove the binding from the MXML, or you could just update the property that is bound but I do not know it's type so I will assume you have no problem removing the binding from the MXML tag.
Second as another answer mentioned you will want to convert your results to an ArrayCollection, you can find some useful functions in the mx.utils.ArrayUtil class.
Lastly it is important when working with large datasets you should update the ArrayCollection directly rather than always creating a new one. The list/datagrid will automatically redraw and update, optimally, without you having to worry about it as long as you add/remove/etc through your newly created ArrayCollection.

Related

Why doesn't my listCollectionView show new items added to the underlying list (in flex)?

I have an (empty) ArrayCollection that I wrap with a ListCollectionView.
Then I add a series of items to the ArrayCollection, but these are not showing up in the view.
public var transactions : ArrayCollection = new ArrayCollection();
public var filteredTransactions : ListCollectionView = new ListCollectionView(transactions);
transactions contains 150 items, filteredTransactions contains none. I originally thought it was the filter I was applying, but even when I remove the filter, I still get no items in the filtered list.
Have I missed a step?
Do I need to add the items to the view as well as the underlying collection (this would seem to defeat the purpose of using a view though...)?
If you aren't using addAll, addItem, or addItemAt to put items in the ArrayCollection, try that as a solution first. Adding items directly to the Array that the ArrayCollection wraps will not dispatch CollectionEvents.
Also, try to use the ListCollectionView's refresh() method after setting its list property to the ArrayCollection.
If neither of these solutions work then please post additional code.

HowTo access correct data inside an AdvancedDataGridColumn-ItemRenderer?

How can I access the specific .data (based on its dataField) inside an AdvancedDatagridColumn-ItemRenderer instead retrieving the whole data for the parent AdvancedDataGrids dataprovider?
Any idea?
Many thanks...
In an itemRenderer, your dataProvider's object is passed in to the data property of the itemRenderer. Your itemRenderer will need to implement the IDataRenderer interface
http://livedocs.adobe.com/flex/3/langref/mx/core/IDataRenderer.html
Most Flex Framework Components already implement this interface.
The way that the DataGrid component works internally is to call an itemToLabel function ( http://livedocs.adobe.com/flex/3/langref/mx/controls/listClasses/AdvancedListBase.html#itemToLabel() ) to figure out the label to display. This function will look at the dataField and dateFunction and return a string representing your item.
The results of this function are passed into the itemRenderer as part of the AdvancedDataGridListData class. Take a look at the label property:
http://livedocs.adobe.com/livecycle/8.2/programLC/common/langref/mx/controls/advancedDataGridClasses/AdvancedDataGridListData.html
You can also use DataGridListData.owner to access the dataField directly, although that would be an unusual approach.

What does {variable} do in flex

I have been using { } around variables in MXML without really understanding what they are for. I am now needing to know if I should use it around a variable..what does that do?
example: <mx:label text="{variable}"/>
That's a binding!,
In this case, it means that the text of the label will show the content of "variable", if you change the value of "variable" it will also change the text displayed by the label.
As stated above, this is will bind a variable to that object.
<mx:label text="{variable}"/>
This will bind variable to the label, so that whenever variable is changed, the text in the label will also change. One other thing to keep in mind would be that you have to set the variable to be Bindable like so:
<mx:Script>
...
[Bindable]
private variable:String = "Label";
...
</mx:Script>
The {braces} formation lets you set a control to respond when a label changes. Any variable that is marked with a [Bindable] attribute like this:
[Bindable]
public var s:String;
can be placed in binding statement.
Keep in mind that if you want to bind to an array that you should use an ArrayCollection rather than a standard Array, because ArrayCollection implements IList and ICollectionView, which allows it to fire updates to the control whenever an item is added or removed from the collection, and arrays require the control to be manually updated to keep in sync.
As stated several times already, that is indeed a data binding. There is a nice little article from adobe on using data bindings in flex.

Can I add an event listener to a databinding action in Flex?

I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.
How can I do this?
Flex doesn't have a specific data-binding events in the way that say ASP .Net does. You have to watch for the dataProvider property like John says in the first answer, but not simply to the combobox or its dataProvider property. Let's say you have a setup like this:
<!-- Assume you have extracted an XMLList out of the result
and attached it to the collection -->
<mx:HttpService id="svc" result="col.source = event.result.Project"/>
<mx:XMLListCollection id="col"/>
<mx:ComboBox id="cbProject" dataProvider="{col}"/>
Now if you set a changewatcher like this:
// Strategy 1
ChangeWatcher.watch(cbProject, "dataProvider", handler) ;
your handler will not get triggered when the data comes back. Why? Because the dataProvider itself didn't change - its underlying collection did. To trigger that, you have to do this:
// Strategy 2
ChangeWatcher.watch(cbProject, ["dataProvider", "source"], handler) ;
Now, when your collection has updated, your handler will get triggered. If you want to make it work using Strategy 1, don't set your dataProvider in MXML. Rather, handle the collectionChange event of your XMLListCollection and in AS, over-write the dataProvider of the ComboBox.
Are these exactly the same as a databound event? No, but I've used them and never had an issue. If you want to be absolutely sure your data has bound, just put a changeWatcher on the selectedItem property of your combobox and do your processing there. Just be prepared to have that event trigger multiple times and handle that appropriately.
You can use a mx.binding.utils.ChangeWatcher as described here.
You can use BindingUtils to get notified when the dataProvider property of the combo box changes:
BindingUtils.bindSetter(comboBoxDataProviderChanged, comboBox, "dataProvider");
BindingUtils lives in the mx.binding.utils package.
I have a longer description of how to work with BindingUtils here: Does painless programmatic data binding exist?
You can also listen for the ResultEvent.RESULT on the HTTPService, that would be called slightly before the combo box got populated I guess, but it might be good enough.
Where are you adding the listener compared to the loading of the data? Is it possible the data is being loaded, and the event fired, before you've added your listener?
#Herms
The listener is definitely added before the web service call, here is an example of what my code look like (I simplified lots of things...):
I have this flex component:
public class FooComboBox extends ComboBox
{
private var service:HTTPService = null;
public function ProjectAutoComplete()
{
service = new HTTPService();
service.url = Application.application.poxmlUrl;
service.addEventListener(FaultEvent.FAULT,serviceFault);
service.addEventListener(ResultEvent.RESULT,resultReturned);
this.addEventListener(FlexEvent.DATA_CHANGE,dataChange);
}
public function init():void
{
var postdata:Object = {};
postdata["key"] = "ProjectName";
postdata["accountId"] = Application.application.accountId
service.send(postdata);
}
private function resultReturned(event:ResultEvent):void
{
this.dataProvider = service.lastResult.Array.Element;
// thought I could do it here...but no luck...
}
private function dataChange(e:FlexEvent):void
{
// combobox has been databound
mx.controls.Alert.show("databound!");
}
...
}
and then in a mxml file I have the FooComboBox with id "foo" and I call:
foo.init();
I need to execute some code after the combobox is completely databound...any ideas?
Maybe the event doesn't trigger when the data provider is first set? Try setting the data provider to an empty array in the constructor, so that it's definitely changing instead of just being initially assigned later in your resultReturned() method. I've no clue if that will help, but it's worth a shot.
Also, you're setting the provider to lastResult.Array.Element. That looks a little suspicious to me, as the data provider should probably be an array. Granted, I have no clue what your data looks like, so what you have could very well be correct, but it's something I noticed that might be related. Maybe it should just be lastResult.Array?
In your example code, try running validateNow() in the resultReturned method. That will force the combo box to commit its properties. The thing is that even though the property is set the new value isn't used until commitProperties is run, which it will do at the earliest on the next frame, validateNow() forces it to be done at once.

Flex: does painless programmatic data binding exist?

I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and please, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.
There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: is there a way to do data binding programmatically that doesn't involve a world of hurt?
Don't be afraid of MXML. It's great for laying out views. If you write your own reusable components then writing them in ActionScript may sometimes give you a little more control, but for non-reusable views MXML is much better. It's more terse, bindings are extemely easy to set up, etc.
However, bindings in pure ActionScript need not be that much of a pain. It will never be as simple as in MXML where a lot of things are done for you, but it can be done with not too much effort.
What you have is BindingUtils and it's methods bindSetter and bindProperty. I almost always use the former, since I usually want to do some work, or call invalidateProperties when values change, I almost never just want to set a property.
What you need to know is that these two return an object of the type ChangeWatcher, if you want to remove the binding for some reason, you have to hold on to this object. This is what makes manual bindings in ActionScript a little less convenient than those in MXML.
Let's start with a simple example:
BindingUtils.bindSetter(nameChanged, selectedEmployee, "name");
This sets up a binding that will call the method nameChanged when the name property on the object in the variable selectedEmployee changes. The nameChanged method will recieve the new value of the name property as an argument, so it should look like this:
private function nameChanged( newName : String ) : void
The problem with this simple example is that once you have set up this binding it will fire each time the property of the specified object changes. The value of the variable selectedEmployee may change, but the binding is still set up for the object that the variable pointed to before.
There are two ways to solve this: either to keep the ChangeWatcher returned by BindingUtils.bindSetter around and call unwatch on it when you want to remove the binding (and then setting up a new binding instead), or bind to yourself. I'll show you the first option first, and then explain what I mean by binding to yourself.
The currentEmployee could be made into a getter/setter pair and implemented like this (only showing the setter):
public function set currentEmployee( employee : Employee ) : void {
if ( _currentEmployee != employee ) {
if ( _currentEmployee != null ) {
currentEmployeeNameCW.unwatch();
}
_currentEmployee = employee;
if ( _currentEmployee != null ) {
currentEmployeeNameCW = BindingUtils.bindSetter(currentEmployeeNameChanged, _currentEmployee, "name");
}
}
}
What happens is that when the currentEmployee property is set it looks to see if there was a previous value, and if so removes the binding for that object (currentEmployeeNameCW.unwatch()), then it sets the private variable, and unless the new value was null sets up a new binding for the name property. Most importantly it saves the ChangeWatcher returned by the binding call.
This is a basic binding pattern and I think it works fine. There is, however, a trick that can be used to make it a bit simpler. You can bind to yourself instead. Instead of setting up and removing bindings each time the currentEmployee property changes you can have the binding system do it for you. In your creationComplete handler (or constructor or at least some time early) you can set up a binding like so:
BindingUtils.bindSetter(currentEmployeeNameChanged, this, ["currentEmployee", "name"]);
This sets up a binding not only to the currentEmployee property on this, but also to the name property on this object. So anytime either changes the method currentEmployeeNameChanged will be called. There's no need to save the ChangeWatcher because the binding will never have to be removed.
The second solution works in many cases, but I've found that the first one is sometimes necessary, especially when working with bindings in non-view classes (since this has to be an event dispatcher and the currentEmployee has to be bindable for it to work).
It exists as of today. :)
I just released my ActionScript data binding project as open source: http://code.google.com/p/bindage-tools
BindageTools is an alternative to BindingUtils (see the play on words there?) that uses a fluent API where you declare your data bindings in a pipeline style:
Bind.fromProperty(person, "firstName")
.toProperty(firstNameInput, "text");
Two-way bindings:
Bind.twoWay(
Bind.fromProperty(person, "firstName"),
Bind.fromProperty(firstNameInput, "text"));
Explicit data conversion and validation:
Bind.twoWay(
Bind.fromProperty(person, "age")
.convert(valueToString()),
Bind.fromProperty(ageInput, "text")
.validate(isNumeric()) // (Hamcrest-as3 matcher)
.convert(toNumber()));
Etc. There are lots more examples on the site. There's lots of other features too-come have a look. --Matthew
Edit: updated APIs
One way to separate the MXML and ActionScript for a component into separate files is by doing something similar to the ASP.Net 1.x code behind model. In this model the declarative part (the MXML in this case) is a subclass of the imperative part (the ActionScript). So I might declare the code behind for a class like this:
package CustomComponents
{
import mx.containers.*;
import mx.controls.*;
import flash.events.Event;
public class MyCanvasCode extends Canvas
{
public var myLabel : Label;
protected function onInitialize(event : Event):void
{
MyLabel.text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";
}
}
}
...and the markup like this:
<?xml version="1.0" encoding="utf-8"?>
<MyCanvasCode xmlns="CustomComponents.*"
xmlns:mx="http://www.adobe.com/2006/mxml"
initialize="onInitialize(event)">
<mx:Label id="myLabel"/>
</MyCanvasCode>
As you can see from this example, a disadvatage of this approach is that you have to declare controls like myLabel in both files.
there is a way that I usually use to use mxml and action script together: All my mxml components inherit from a action script class where I add the more complex code. Then you can refer to event listeners implemented in this class in the mxml file.
Regards,
Ruth

Resources