Wednesday, December 19, 2007

Introduction to Datagrids

Datagrids give largest possible options for user to interact with data. This brings performance and size overhead to be kept in mind.

Use editable property to make the grid uneditable. draggableColumns property used to enable/disable column resizing (true by default). variableRowHeight property used to tell Flex to resize row's height according to renderer. The columns for the grid can be specified within <mx:columns> tags. Useful when we want the order of columns to be different from what is received.

Each column is specified using <mx:DataGridColumn> tag. Use its dataField property to specify the field to use to populate, headerText to give column header and editable to determine if it is editable (The parent grid has to be editable for this).




<mx:DataGrid id="myGrid" editable="true" draggableColumns="false">
   <mx:columns>
      <mx:DataGridColumn dataField="field1" headerText="Field1 Data" editable="false"/>
      <mx:DataGridColumn dataField="editableField" headerText="Input"/>
   </mx:columns>
</mx:DataGrid>


Q&A
  1. How can you make a DataGrid editable?
  2. How do you control column resizing in a DataGrid?
  3. What will you do if you want the order of columns to be different from the order of data received in a DataGrid?
  4. Briefly explain the steps involved in initializing a column in a DataGrid.

Monday, December 17, 2007

And Then There Was AIR

Kapil and myself have started exploring AIR by Adobe (code-named Apollo) and, man, is it exciting or what. For more, see:

http://labs.adobe.com/technologies/air/

I will be back with more :).

Wednesday, December 12, 2007

Datasets: Using Repeater

We can loop over a data set in MXML using a Repeater component. General syntax for Repeater is:

<mx:Repeater id="myRepeater" dataProvider="{someColl}"> </mx:Repeater>

It will loop once for each object in the data set. currentItem property is reference data item being processed. currentIndex property is a zero-based counter indicating position of the current item in the data set. But these will be useful only during looping.

After the looping is finished we need to get data from the items that may have been created dynamically inside the Repeater. For this Repeater has getRepeaterItem() method that returns the item in dataProvider property that was used to make the item as an Object type. This can be used on the appropriate event (say click). The code would look like:

<mx:Repeater id="myRepeater" dataProvider="{someColl}"> <mx:RadioButton label="{myRepeater.currentItem.name}" click="someFunc(event.target.getRepeaterItem())"/>
</mx:Repeater>

The properties of the object this obtained can be used as desired.


Another issue is addressing the components created using Repeater. You give an id in the loop. Flex will create an array of the items created by the name of the id. Using the array index individual items may be accessed. The code

<mx:Repeater id="myRepeater" dataProvider="{someColl}"> <mx:RadioButton label="{myRepeater.currentItem.name}" id="myrb" click="someFunc(event.target.getRepeaterItem())"/>
</mx:Repeater>

will create array myrb. Individual information may be accessed using index as
myrb[0].label

TileList control instantiates objects when they are displayed whereas a Repeater inside a Tile container instantiates all the objects in the entire dataset, whether they are initially displayed or not. Depending on size of data, this may delay rendering on the flash player. However scrolling will be better once the page loads in this case as everything is there. If dataset is small, difference will not be noticable. But for bigger sets one has to think and decide.

Q&A

  1. Why would you use a Repeater component?
  2. How can you get data from the items that may have been created dynamically inside a Repeater?
  3. Ho do you address the components created using a Repeater?
  4. What is the alternative to using Repeater?
  5. What is the difference between using a TileList control and a Repeater? How will you decide when to use what?

Tuesday, December 4, 2007

Flex Components: Understanding Containers

Flex containers consist of two distinct sections: layout area where the children are drawn and chrome area which has borders, backgrounds, margins, scrollbars,headers, footers etc. In Panel class title bar is implemented as chrome.

The base class flash.display.DisplayObjectContainer does not make any distinction between child components and chrome. But the mx.core.Container class (superclass of all Flex containers) overrides several methods including getChildAt() and numChildren() to give the appearance that the container's only children are child components. To gain access to all elements we need to use the rawChildren property. In panel anything added using addChild() will be rendered below title bar. To add elements to title bar you will need to use this property. eg: rawChildren.addChild(myButton);

However this will only add but not size/position the children in the chrome. To do that we need to override the updatedDisplayList() method. This is called everytime the component is redrawn. Be sure to call super.updatedDisplayList() so as the correct rendering happens for the rest of the component. The method is passed two attributes, unscaledHeight and unscaledWidth, which are the actual height and width of component regardless of any scaling.

Q&A
  1. What do you understand by chrome?
  2. How can you customize the title bar of a Panel class?

Monday, October 8, 2007

DataSets In Flex: Basic

There are two approaches to dealing with data sets:
1.Using a Repeater in MXML
2.Use data set as a dataProvider

List based controls enable user to scroll through a list of items and select one or more items from the list. All Flex-based list components inherit from ListBase class. They include:
DataGrid, HorizontalList, List, ComboBox, TileList, Tree
They all have the dataProvider property

The property displayed by the list can be specified in labelField property. This is ok if we wish to use one property as label. If we wish to combine various properties, we have to write a function and assign it to labelFunction property. eg:
this function
private function multiPropComboLabelFunc(item:Object):String{
return "label for"+item.name+","+item.id;
}
may be given as
<mx:HorizontalList dataProvider="{myCol}" labelFunction="multiPropComboLabelFunc"/>

Notice that even when there is a parameter to the function in script, the same need not be given in the tag. Flex automatically passes the correct object.

By default HorizontalList and TileList permit only text to be displayed. This can be overridden using the itemRenderer property. itemRenderer can be an mxml component made to customize the display as desired. When you specify the file to be used as itemRenderer, you do not specify the extension (which can be .mxml or .as). The data passed to the renderer will be in an object called "data".

Questions:
  1. How will you determine what is displayed by a list control?
  2. If you want to display more that text in a list based control, how can you do it?

Thursday, October 4, 2007

Getting A Screenshot/ Screengrab in Flex

While developing your RIA you may, like me, feel a need for taking a screen shot. This you may want to use in your reports or for a static page.

Solution

Tuesday, October 2, 2007

Event Bubbling in Flex

Event target may or may not be visible on screen. If not visible (like HTTPService), flash player dispatches event directly to the target. If visible, event flow is divided in three phases:
1. capture phase: flowing from base application to target
2. target phase
3. bubble phase: flow from target to base (reverse of 1)

This design enables using event listeners on any node in the flow. Was not there before Flex2. Due to this an even in the child can be heard by parent. All instances of the Event class have a bubbles property which indicates if event object will participate in bubbling phase. By default false for newly built events; Event class takes it as a second optional parameter set to false by default. Default true for some built in events like click.

You do not need to handle a bubbling event in between but you need to have it declared in the metadata so that the parent component may be able to hear it.

Remember that only custom events need to be enumerated explicitly with a metadata tag. But if they are of base Event type, we can simply mention them after import statements but before class declaration using [Event(name="someEvent")] metadata tag.

Questions:
  1. Explain event bubbling in flex.
  2. What are the advantages of event bubbling?
  3. How do we know if an event object will participate in the bubbling phase?
  4. Explain event flow in flex.

Friday, September 28, 2007

Flex Components: Using AS3.0 To Build Components

Generally we build custom components using MXML. If more flexibility is needed then AS3.0 should be used. More powerful.

To create a component decide which class to extend, methods to implement/override and properties. Take care that you will need to declare any events that the component will dispatch. For visual components we will need to override createChildren() and updateDisplayList() methods as they are needed by flex to create children.

To embed a resource into the component use [Embed("../pathToAsset/asset.jpg")] metadata tag and follow with declaration of a property name to be used to hold reference to the same data-typed to Class.

On the backend when we create a component, the initialization sequence is as follows:
Constructor
createChildren()
commitProperties()
measure()
updateDisplayList()

In most cases we will need to override createChildren() and updateDisplayList().

commitProperties() override needed if we need to set properties dependent on other properties already set. Called after all children have been created.

measure() override needed if we want to manually calculate height and width of all the children created. Used to contain new containers with unique layout rules.

Children can be created and added to a component using addChild() and addChildAt() methods

Questions:
  1. How will you embed a resource into a component?
  2. What is the initialization sequence when a component is created (key methods)?
  3. In the sequence in Q2, which methods will you need to override? Explain.
  4. How can you create children for a component?

Thursday, September 27, 2007

Flex Events: Introduction

Using events enables a loosely coupled architecture. To broadcast an event from a component you need to use the dispatchEvent method. This method is defined in the flash.events.EventDispatcher class. Observer pattern.

You need to declare the events that may be dispatched by a component. A component may dispatch any event declared by any of the superclasses

In Flex events can be declared using metadata tag [Event], which is used to declare the event publicly so that the MXML compiler recognizes it.
<mx:Metadata>
[Event(name="eventName",type="flash.events.Event")]
</mx:Metadata>
We can specify type. If not mentioned, default is flash.events.Event
The name used here is used to initialize the event type parameter before it is dispatched i.e.
var e:Event = new Event("eventName");

Now when this component is initialized, we can use the event name like any other attribute and specify a function to call
<m:CustomComponent id="myComp" eventName="someLocalFunction()"/>

Many times we may also need to pass around data with the events. Cannot be done with the basic flash.events.Event class. But we can create an event subclass. You will generally need to override clone method of the Event class

Summarizing, we will have these elements in event handling:
1. The event class: you can extend the Event class. clone method is overridden then and the data that we expect the event to carry is member var
2. Event dispatching component: Generally a UI component will dispatch the event after creating in at the appropriate function. The component declares all the events it can dispatch.
3. The listener/event target component/app: This is generally the parent/top level component that uses the event dispatching component. If it is interested in any event dispatched by it, it handle it by listening to it.

Questions
  1. Why should you use events?
  2. What design pattern does events mechanism employ?
  3. How will you declare an event?
  4. What is default event type?
  5. Why would you use a custom event?
  6. With a small example and code explain how events work in flex.

Tuesday, September 25, 2007

Road To Flex-7

At runtime you can add a property to an Object as:
var myObj:Object = new Object();
myObj.someID=new Array();
Like javascript...
If you are using e4x notation to get the property name dynamically, you will have to enclose it in square brackets ie
myObj[c.@someID]=new Array();

implementing toString method in the AS classes will help in tracing.

to remove extra tabs select all and use Shift+Tab key combo in the eclipse based flex editor

Use source property of the Script tag to specify external script.

In AS3.0 we can override functions. For this they should have the same access specifier (public/private), have same number & type of parameters in the same order and should be explicitly preceded by the keyword override.

<mx:metadata> tag can be used to declare metadata

Questions:
  1. How do you override functions in AS3.0?
  2. Which tag will you use to declare metadata?
  3. How will you specify an external file for the Script tag?
  4. How will you add a property to an object at runtime?

Friday, September 21, 2007

Flex Components: Introduction

Why do we need to make components? Helps organize the code, make it modular. The aim most of the times will be to either add functionality to a pre-defined component or group numerous components together.

The general approach is
1. Plan what you want your component will be, what will it do and where it will lie in the hierarchy. Choose an appropriate name.
2. First line will be the XML DTD we are using with the main application. No application tags as one app can have only one.
3. As the first MXML tag we insert the root tag of our component
4. In tag body add the functionality
5. In the file where we want to use the component we add an XML namespace so as we can access the component
6. Instantiate the component as any predefined component.
eg: Lets say we want a component to extend a TitleWindow, skeleton may look like:
<?xml version="1.0" encoding="utf-8"?>
<mx:TitleWindow xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
</mx:TitleWindow>
Say we create it at location ui.popups by name DataPopup. We will add namespace in Application tag in the main file as: xmlns:p="ui.popups.*"
and then instantiate in the body at appropriate place as:
<p:DataPopup/>
All the properties that we put in the script element in component can be instantiated as properties in the instantiation like property of any other component

UIComponent is the lightest-weight component that you can use when creating an MXML component. It is ideal to use for root tag of non-visual data manager type of components.

You cannot assign id to root tag of a component

It is a good idea to bundle a few UI components in a canvas tag to control mouse events on all of them. Combine it with currentState to get appropriate changes in the ui, including mouse hovers.

The inheritance hierarchy of UIComponent class:
mx.core.UIComponent extends
flash.display.Sprite extends
flash.display.DisplayObjectContainer extends
flash.display.InteractiveObject extends
flash.events.EventDispatcher (superclass of all flex components)

Questions:
  1. Why do we need components?
  2. Explain in brief how you would go about making a component?
  3. What base component would you use to make a non-visual component?
  4. What is the inheritance hierarchy of UIComponent class?

Thursday, September 20, 2007

Road To Flex-6

for loop has two flavors in AS3.0. One is the regular vanilla: for(var i:int;i<somecol.length;i++){}. The other looks like this: for each(var p:Object in someCollection){}.

You can call a function from the parent MXML document as:
if(this.parentDocument.parentFunction!= null){
this.parentDocument.parentFunction(param1);
}
But this is not a good practice. Can be handled using events.
Another not so good way for a component to call a function from the top level application:
mx.core.Application.application.funcToCall(params);

Use TitleWindow class+PopUpManager class to make a modal window. TitleWindow well suited. Has a showCloseButton property.

To create a popup using PopUpManager, use PopUpManager.createPopUp(parent, popUpWinClass, isModal); This method returns IFlexDisplayObject.

Use PopUpManager.removePopUp(this); to execute the actual close ie removing the popup.

UIComponent -> Container, Button, NumericStepper, ComboBase
Container -> Box, Form
Box -> VBox, HBox
ComboBase -> ComboBox

Questions:
  1. Your child component need to call a function from the parent component. How will you handle it?
  2. A component needs to call a function from the top level application. How can this be done?
  3. How would you work on making a popup?
  4. What is syntax for the for loop in AS3.0?

Wednesday, September 19, 2007

Road To Flex-5

  • addItem() method of the ArrayCollection does the same thing as push() method of Array
  • Making an XMLListCollection in MXML pointing to HTTPService data <mx:XMLListCollection id="myList" source="{serviceId.lastResult.family}"/>
  • XMLListCollection is very much like ArrayCollection except that it is used for XML data. It is a best practice to bind to an XMLListCollection instead of the native XML object. Useful to use it for Tree control.
  • In AS3.0 we can specify functions with parameters and give a default value to them. Such params if lying at the end are optional while calling the function
  • AS3.0 has native XML support in the form of ECMAScript for XML(E4X). E4X specs define a set of functionalities and classes for working with XML data. These are collectively called E4X.
  • XML class in AS3.0 is NOT the same as XML class in AS2.0. That class has been renamed as XMLDocument.
  • RichTextEditor allows user to markup the text entered into the control.
  • You can use as operator to cast an object. Collection lists generally return an object type (remids me of Java in pre Java5 days) and needs to be cast. Eg. You have a ArrayCollection col1 which holds objects of type myObject. You have function which need object of this type, function func1(data:myObject): void{}. The call to this function using an item retrieved from the collection may look like this: func1(col1.getItemAt(0) as myObject). If you dont fo do that, it gives an implicit coercion error.
Questions:
  1. What is the difference between XML class in AS2.0 and AS3.0?
  2. When would you use a RichTextEditor?
  3. Why would you use the as operator?
  4. What is E4X?

Tuesday, September 18, 2007

Working With Data in Flex: E4X

When using E4X notation, root node is not used in statements.

E4X makes dealing with AS XML objects much easier and flexible. Eliminates the need to build complicated for loops to obtain data. Was not there before 3.0.

Let us see some key E4X operators

dot [.] operator allows to navigate to a particular node type. Eg:
for XML:
private var myXML:XML = new XML();
myXML=
<parent>
   <family>
      <child age="2" weight="10">
         <name>child1</name>
         <id>0</id>
      </child>
       <child age="2" weight="15">
         <name>child2</name>
         <id>1</id>
       </child>
   </family>
   <family>
      <child age="4" weight="17">
          <name>child3</name>
         <id>2</id>
       </child>
      <child age="5" weight="20">
          <name>child4</name>
         <id>3</id>
      </child>
    </family>
</parent>

now,
myXML.family.child.name
would give
<name>child1</name>
<name>child2</name>
<name>child3</name>
<name>child4</name>

parantheses [()] operator allows to get node using condition
eg:
myXML.family.child.(name="child1")
will give
<child age="2" weight="10">
    <name>child1</name>
    <id>0</id>
</child>

attribute [@] operator can be used to do the same thing using an attribute
eg:
myXML.family.child.(@age="2")
will give
<child age="2" weight="10">
    <name>child1</name>
    <id>0</id>
</child>
<child age="2" weight="15">
    <name>child2</name>
    <id>1</id>
</child>
All the nodes matching the criteria are returned

descendant accessor [..] operator allows getting any descendant, no matter how deep they are buried.
myXML..name
will give
<name>child1</name>
<name>child2</name>
<name>child3</name>
<name>child4</name>

When we want E4X format we specify resultFormat in HTTPService:
<mx:HTTPService id="serviceId" url="http://www.myUrl.com/myXml.xml" result="handlingFunc(event)" resultFormat="e4x"/>

Questions:
  1. What is the advantage of using E4X?
  2. In E4X explain the usage of dot [.] operator.
  3. In E4X explain the usage of attribute [@] operator.
  4. In E4X explain the usage of parentheses [()] operator.
  5. In E4X explain the usage of descendant accessor [..] operator.
  6. How will HTTPService know that the format of result returned?

Thursday, September 13, 2007

Working With Data in Flex: Using Cursor

Collections have ability to manipulate and sort data. This uses the concept of "cursor". All classes that implement ICursorView interface have the functionality. Eliminates need of complicated loops.

ArrayCollection implements ICursorView. Before we can use a cursor on it, we need to sort it. For this we use Sort and SortField classes and sort property of the collection.eg:

var cursor:IViewCursor = myArrayCollection.createCursor();
var sort1:Sort = new Sort();
var sortField1:SortField = new SortField("fieldToUse1");
var sortField2:SortField = new SortField("fieldToUse2",false,true,true);
sort1.fields=new Array(sortField1,sortField2);
myArrayCollection.sort = sort1;
myArrayCollection.refresh();

First we make a new instance of Sort. Then we need to make sort fields for the sort ie the property by which the whole collection should be sorted. SortField has one mandatory and three optional parameters with default value of false. First is name of property on which to sort. Second if sort should be case sensitive. Third if it should be descending sort. Fourth if it should be a numeric sort. A Sort can have several fields given to it in an Array. It uses them in the order to sort. In this case it would first sort by field1 and then by field2. Then this sort is given to the collection and refresh method called to sort.

From this point we can various methods on the cursor. The cursor will find using the fields specified for sorting. eg. cursor.findFirst(obj); will see if the obj Object already exists in myArrayCollection and will return true or false accordingly. The search will happen using the sortfield ie field of the Object will be matched with those in the list. We also have findLast and findAny methods. cursor.current gives the current object being pointed to. Dont forget to cast the object obtained. Finally there is the remove() method to remove the object to which the cursor is pointing to.

Questions:
  1. How do you sort/manipulate data in flex collections?
  2. With an example illustrate how you would sort a collection?
  3. How would you ensure that a field is used to sort the collection is case insensitive, ascending and numeric?
  4. What is the use of a cursor?

Wednesday, September 12, 2007

Normal -> AJAX -> AJAJ -> AJAJS

The internet world is moving towards a rich and fast user experience at a very rapid speed. AJAX is contributing majorly in this direction.
AJAX [Asynchronous Javascript And XML] is not a technology, it is a concept built on the existing technology provided by major webbrowsers.
The native XMLHttpRequest object or the Microsoft.XMLHTTP ActiveXObject enables the use of AJAX. Using one of these [as the case may be] objects, the javascript code in a webpage can asynchronously send the HTTP's GET/POST request to a webserver. Javascript can be further used to display the responseText/responseXML anywhere on the existing webpage. This way some text [or image or any other HTML object for that matter] can be changed on the existing webpage without reloading the whole page.
Gmail, Orkut, Google Suggest and many other existing and upcoming sites use this concept extensively.
You can find a detailed explanation and examples of how to implement AJAX in your applications here.

AJAX requires the response from the webserver to be in XML format. To further improve the performance of the application, XML can be replaced by something light in weight. JSON (JavaScript Object Notation) provides a fat free notation of JavaScript objects. AJAJ (Asynchronous Javascript And JSON) does exactly this. By the use of AJAJ you may not have to fetch/parse the responseXML of the HTTP object to extrace the relevant info. The responseText can be directly loaded in the JavaScript variables. The official JSON website demonstrates this with beautiful examples.
There are 2 benifits of using AJAJ over AJAX:
1. JSON is lighter that XML.
2. You do not have to parse JSON on the client side to initialize JS variables, unlike XML.

Going a step further, we may even replace the JSON of AJAJ with JavaScript. I call it AJAJS [Asynchronous JavaScript And JavaScript]. Insead of responding with the responseXML or a JSON in the responseText, the server might respond with a javascript code in the responseText.
And on the client side, you may use the JavaScript eval() function to execute the responseText. So now the responseText can even be a function call.
Eq:
suppose http.responseText = "showMessage('From: chhabra.kapil@naukri.com', 'Subject: Hey!', 'Body: How do you do, buddy! ...')";
Now suppose that showMessage is a function in your javascript that accepts 3 parameters to display an email mesage on the page, you may just
eval(http.responseText)
in your client side JS code.

Monday, September 10, 2007

Working With Data in Flex-2

When retrieving data, one needs to know the structure of XML being fetched. In order to form a collection out of the same on needs to point to the repeating structure. For eg. in the following XML:
<parent>
<child>
<name>child1</name>
<id>0</id>
</child>
<child>
<name>child2</name>
<id>1</id>
</child>
<child>
<name>child3</name>
<id>2</id>
</child>
<child>
<name>child4</name>
<id>3</id>
</child>
</parent>
we would have some function:

[Bindable]
private var resultList:ArrayCollection=new ArrayCollection();

public function getResult(event:ResultEvent):void{
resultList = event.result.parent.child;
}

In this case child is the repeating unit.
When using a list-based control we could directly specify the data from this xml as follows:
<mx:List id="id" rowCount="3" dataProvider="{resultList}" labelField="name"/>
Note that for labelField we have directly specified the name of the node to be used.

The actual call will happen only when the send method is invoked using the id given to HTTPService class. It is prudent to call it on creationComplete event of application if data is to be used application wide. Else on creationComplete of the specific ui objects.

Always use collections instead of arrays for data-binding. Much more useful. By default complex data-structure is returned as an ArrayCollection. Multiple control enable display datastructures using the dataProvider property. List-based controls (List,Tree,DataGrid,TileList,ComboBox) use this property for sure. dataProvider control have a lot of advantage in the sense they are dynamic and can be used to populate multiple controls. UI control data-binding does not happen with AS2.0 Array. You can pass the array to creation constructor of a collection to form a collection with the array elements.

Questions:
  1. What is the advantage of using collections instead of arrays for data-binding?
  2. Explain usage of HTTPService with an example.
  3. When does the call to the URL mentioned in HTTPService happen?

Friday, September 7, 2007

Working With Data in Flex : Using HTTPService

<mx:Model> tag allows you to build a client-side data-model. AS can access it in id.tagName format. When using databinding in MXML, it is indicated by {}. You can either type the tags or specify an external file. Useful to embed data that will not change (like options in option box/label text). Also useful for applications that need data offline. However this data is not typed: can result in poor performance and severly limit error trapping. It is just a simple substitute for server-side data. Can be addressed by using AS class for client side data-structure. Another reason that it is a bad idea is because it embeds XML into the swf. Besides increasing the size it also means that we need to recompile the swf every time we change the XML. A better option will be to pick the XML at runtime using the HTTPService class. It will retrieve XML using HTTP/HTTPS protocol by making a GET or POST request.

HTTPService class can be used to make asychronous calls. send() method of the object is used to send the request. After data has been received, result event (ResultEvent) is broadcast. The result is stored in lastResult property. A resultFormat can be specified or Flex will parse it approproately. Format can be array, e4x, flashvars, object, text or xml.

Flex gives the flexibility to convert to native XML object (E4X) or to directly convert into a object(like ArrayCollection, XMLListCollection).

For automatic conversion, we will have a tag similar to this in the MXML:
<mx:HTTPService id="serviceId" url="http://www.myUrl.com/myXml.xml" result="handlingFunc(event)" fault="handleFault(event)"/>

Use fault event to handle errors. The event in this case will be FaultEvent and not ResultEvent

Questions:
  1. What are the advantages and disadvantages of using a Model tag in flex?
  2. How can you avoid using a Model tag?
  3. Describe in brief how HTTPService class works.
  4. What are possible result formats for HTTPService?
  5. What are the advantages of using HTTPService?
Sample MXML would make sense after a few more writings in this series. This is a very important feature in flex and well worth the time spent on it :) !

Thursday, September 6, 2007

Road To Flex-4

  • All tags added to MXML represent an object
  • creationComplete is a system event, dispatched by flex components after being screen rendered. Application dispatches it after all components drawn and individual components dispatch too.
  • [Bindable] metadata tag, when specified in front of the class keyword, means that every property in the class can be bound to controls or other datastructures. We can also specify individual properties as bindable. Allows changes to be reflected from source to destination.
  • A class constructor is defined using function keyword followed by the name of the class
  • Event class holds a lot of useful information about the event generated. currentTarget property refers to the element which generated the event. type property tells about the event type.

Questions that can be asked:
  1. How can we find out if a ui component has been rendered completely or not in flex?
  2. What is the use of Bindable tag?
  3. How do you define a class constructor in AS?

Tuesday, September 4, 2007

Road To Flex-3

  • To control focus in a form use FocusManager class.
  • <mx:CheckBox> is a regular ui component. selected property determines if checked.
  • <mx:Script> tag to write AS. functions defined can be called by name in control actions (like click for Button). Script written as is between <![CDATA[]]>
  • To display an image we use an Image control. ID property can be used by actionscript to reference the Image class. Scale content property if set to true scales image to container size. Embed directive embeds the image into the swf. eg: source="@Embed('assets/myPic.jpg')". mouseOver/ mouseOut property can be used to change current state.
  • Label control allows you to display a single line of text
  • Text control allows you to display multiple lines of text
  • <mx:Spacer> tag to add space between two controls. Specify width.
  • <mx:DateField> for date based input
  • All radio buttons must belong to a group. data property helps determine which btn selected in a group.
Questions:
  1. Name some common UI controls in flex.
  2. What can you do to control focus in a form?
  3. How can you ensure that a checkbox componenet is selected on creation?
  4. How can you write an actionscript in an MXML?
  5. How can you prevent an image in an image component from scaling?
  6. What effect will an Embed command have on an Image component?
  7. Which component will you use for a date-based input?
Sample MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:Script>
<![CDATA[
import mx.collections.ArrayCollection;

private var categories:ArrayCollection = new ArrayCollection();

private function myFunction():void{
}
]]>
</mx:Script>
<mx:ApplicationControlBar dock="true">
<mx:LinkButton label="Default State" click="this.currentState=''"/>
<mx:LinkButton label="Change State" click="this.currentState='state1'"/>
<mx:Spacer width="100%"/>
<mx:Label text="Date Field"/>
<mx:DateField id="myDate"/>
<mx:RadioButtonGroup id="radioGrp"/>
<mx:RadioButton id="r1"
groupName="radioGrp"
label="Option 1"
data="1"
selected="true"/>
<mx:RadioButton id="r2"
groupName="radioGrp"
label="Option 2"
data="2"/>
</mx:ApplicationControlBar>
<mx:states>
<mx:State name="state1">
<mx:SetProperty target="{mainPanel}" name="width" value="0"/>
<mx:SetProperty target="{mainPanel}" name="height" value="0"/>
</mx:State>
</mx:states>
<mx:Panel id="mainPanel" title="My Panel" height="100%" width="100%">
</mx:Panel>
</mx:Application>

Flex Problems September 2007

Just archiving the flex problems I faced and the solutions that helped me. Will have one of these per month depending on whether I find a problem or not :p.

Problem: This message comes in debug mode: "Installed Flash Player is Not a Debugger. Flex Builder cannot locate the required debug version of the Flash Player. You may need to install the debug version of the Flash Player 9.0 or reinstall Flex Builder. Do you want to try to debug with the current version?"


Solution: Visit this link

The Road to Flex-2

  • All constraints are set relative to edges of a Canvas container (or those that can act as a canvas container like Application, Panel). They cannot be set relative to other controls or containers
  • Constraints help in controlling the view when window size changes
  • View state is one of the several views that you define for an application or a custom component. Every MXML page has at least one state, referred to as the base view state.
  • Each MXML page has a property called currentState that can be used to control which state of application to show to the user at any given time.
  • Setting currentState to blank string resets app to initial state
  • Forms are needed to collect info from users. In flex form containers can designate fields as optional or required, handle error messages and do validations. Form container uses <mx:Form>, <mx:FormHeading>, <mx:FormItem>. <mx:Form> is outermost tag and always arranges children in vertical fashion and left aligns them. We can have multiple heads. Form heading enable to specify label for a group of form items. Form item will automatically supply one label control. Other controls are added within tags and follow the label. By default all controls laid vertically right to the label. To change one needs to specify 'direction' property.
Questions:
  1. How are view constraints set in Flex?
  2. What is the use of having such constraints?
  3. What is the use of view states?
  4. What is the use of the property currentState?
  5. What will happen if the property currentState is set to a blank string?
  6. What is the use of forms in flex?
  7. How many heads/headings can a form have?
  8. What is the default layout for controls in a form? How can that be changed?
A sample MXML showing use of forms:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
<mx:Form>
<mx:FormHeading label="Form Heading"/>
<mx:FormItem label="Item1 Name">
<mx:TextInput id="item1Txt" text=""/>
</mx:FormItem>
<mx:FormItem label="Item2 Name">
<mx:TextInput id="item2Txt" text=""/>
</mx:FormItem>
<mx:FormItem label="Item3 CB">
<mx:CheckBox id="cb1" selected="true"/>
</mx:FormItem>
<mx:FormItem>
<mx:HBox>
<mx:Button label="Save"/>
<mx:Button label="Cancel"/>
</mx:HBox>
</mx:FormItem>
</mx:Form>
</mx:Application>

Thursday, August 30, 2007

The Road to Flex-1

AJAX is good and I am already finding very good books and tutorials for the same on the web and the internet. But with Flex things are different, especially in India. Good books are still not available and I am not very happy with the internet resources.

So, here I am starting a compilation of what I have learned in flex 2.0 as it comes to me basis. I am not trying to make a tutorial YET. But what I am trying is compiling the basics for anybody who may find it useful. If it helps even one guy, this is going to be worth it:). Any comments welcome!

Everyday or so I will mention few things I learned about Flex 2.0 , possible interview questions one could frame using them and a sample MXML demonstrating the point. In "Road To Flex" series I will clobber whatever I learnt and feel I cannot put under one general topic. Specific topics/problems would invite separate entries from time to time.

My resources are the internet and Training from the Source book by Adobe.

For today:
  • You can have only one <mx:Application> tag per Flex application
  • UI Layout in an application can be absolute, vertical or horizontal.
  • All layout in flex is done using containers:VBox, HBox, Canvas, Application, Tile, Panel, ControlBar, ApplicationControlBar
  • ControlBar is used to dock a toolbar to the bottom of a panel container or a titlewindow container
  • ApplicationControlBar used to hold components that provide access to elements used throughout an application. If specified as first child of <mx:Application> tag and dock attribute set to true, docks at top of app's draw area, extends full width and does not scroll.
Interview questions that can be asked for these points:
  1. How many <mx:Application> tags can a flex application have?
  2. What are possible values for UI Layout?
  3. Name some containers used by Flex.
  4. Which container will you use to make a toolbar?
  5. What is the use of an ApplicationControlBar?

A sample MXML demonstrating some of the points:

<?xml version="1.0" encoding="utf-8"?>
<mx:application mx="http://www.adobe.com/2006/mxml" layout="horizontal">
<mx:applicationcontrolbar dock="true">
<mx:linkbutton label="Link1"/>
<mx:linkbutton label="Link2"/>
</mx:ApplicationControlBar>
<mx:panel id="panel1" title="My Panel">
<mx:Controlbar></mx:ControlBar>
</mx:Panel>
<mx:VBox id="vertBox">
<mx:panel id="panel2" title="Panel Inside">
<mx:controlbar></mx:ControlBar>
</mx:Panel>
</mx:VBox>
</mx:Application>

Thursday, July 12, 2007

The Beginning

My quest with AJAX has taken me on different roads in the past few months. AJAX talks of the promise to be able to build "Rich Internet Applications" (RIAs). But that we already know. What we want to know now is its limits and if there is something beyond that.

Exploring all the frameworks/libraries available wrt AJAX, I find yui to be the most well written, extendible and documented. I would recommend yui to anybody who wants to make an AJAX based application, wants to learns more about AJAX, wants to improver his/her javascript(js) knowledge or develop their own widgets. A lot of good, reusable, well documented, well written code there. Kudos.

AJAX demands extensive use of javascript and more often than not you do end up having a lot of duplicate logic on the browser and push the browser to its limits. Cross-browser issues come if you dont test extensively. And there is this unholy mixing of model with the view with the controller. Like java swings architecture, one may digest somewhat tighter coupling with the view and the control. But when it comes to data, it makes me nervous when I have to mix it with the view. With the ability to segregate code using javascript object, this problem can be handled to some extent as yahoo have done it. But it is there to some extent.

AJAX is to stay. But there is something else that is grabbing my attention these days: flex. What about flex? Will come back with it soon!