Showing posts with label technical. Show all posts
Showing posts with label technical. Show all posts

Saturday, October 15, 2011

Launched a new site for Bangalore Volvo Route planning

I have created a web application ( http://bmtcroutes.in/ )that helps user to find the BMTC volvo bus routes between places in Bangalore.

You might have come across some of the sites which provides the same functionality but I have tried to add some new features that are missing in the existing sites.

1. It allows the user to enter free text to search for an address. It takes care of common spelling mistakes like instead of typing Marathahalli user typed Maratahalli

2. Some places are more commonly called by their old names. For e.g. Majestic, the application takes care of such scenarios. Most of the addresses in bangalore are already listed so the user will get the suggestions about then once he starts typing the search string, but in case it is not listed the user can still enter the address and the application will try to find the route for it too. No similar application has got this capability.


3. Most of the similar applications searches only for the direct bus routes i.e. both source and destination should be covered by the same bus which is a serious restriction given possibility of indirect routes is very high. bmtcroutes.in is the first application that can search for the indirect routes with high degree of precision.


4. Provides a very intuitive UI. Since the application is targeted to both technical and non-technical users, the simplified UI is key requirement.

5. The application can be accessed from multiple channels : Website, Mobile app, SMS based interactions. (Currently it is available only through webbased interface but I will cover others soon)


I have focussed more on the functionality, so could not get time to make it jazzy as per todays standards but then it is VERSION 1

Currently the buses are restricted to BMTC Volvos, Big Circle and Airport Volvos, but based on the demand I can extend it to non-volvo buses too.
I have tested the site for firefox and chrome...I did not test much for IE

Sunday, June 19, 2011

Can Semantic web improve the shortcomings of Keyword Search?

Currently most of the popular search engines are based on the keyword search algorithm which means, they try to search for the pages which contain the keywords entered by the user and provide you the results. There are certain problems with the keyword based search mechanisms which can be understood by taking few common scenarios (I have taken few examples from the book Social Networks and the Semantic Web by Peter Mika. I have added my explanations to make these scenarios easy to understand):
1. Who is Frank van Harmelen? (Basic keyword based search)
Suppose I want to query this with the search engine like Google. And I entered the keyword Harmelen. Google has no idea about my intentions it will just do a keyword search and return me the results that will be about persons with some portion of name as Harmelen, some product on Amazon whose name is Harmelen and so on . Basically if we look into the conversation mode then the query that we did and the response from the search engines will look like
Q: Who is Frank van Harmelen?
A: I don’t know but there are over a million documents with the word “harmelen” on them and I found them all really fast (0.31s). Further,you can buy Harmelen at Amazon. Free Delivery on Orders Over 15.

Upon closer inspection the problem becomes clear: the word Harmelen means a number of things. It is a name of few people (Frank van Harmelen or Mark van Harmelen etc). Harmelen is also a small town in the Netherlands and the place for a tragic train accident. There is also some products on Amazon with the name Harmelen. So basically the search engine has thrown a wide range of results.

We will then start adding some more information to the keywords and will specify the full name that we are interested in “Frank van Harmelen”.
This will reduce the result set but still there are lot of extra results. For e.g. the user might be interested in Frank van Harmelen, Professor of Vrije University. But the result will have the web pages containing any Frank van Harmelen

The user can further refine the search results by typing more keywords “Frank van Harmelen professor of Vrije University” which will return pages containing the correct Frank van Harmelen.
So if we analyze the refinements we are basically providing more and more information in the keywords to guide the search engine to return the correct results.

Still there are some problems in the results. There can be multiple scenarios where the even though information on the page is relevant to the Frank Van Harmelen but we are not getting them on the search results. There might be webpages where the name is not mentioned as Frank van Harmelen but still they have been written by Frank or there are web pages who are referring to Frank van Harmelen as “he” or Frank might have written some articles/books which the webpage is referring as FVH98.
The search engine will miss out these pages which can be quite relevant to the person who is querying since it has got no information that the pages related to Frank Van Harmelen

There are some common queries that user wants to perform but are impossible with the current searching mechanism. For e.g. a movie buff might want to search “Give me all the movies which were directed by Steven Spielberg and acted by Harrison Ford”.
The search engine will just return the pages where both of them are listed together. The search cannot understand the meaning of the web pages and cannot figure out if the page is indicating that two of them have worked together or it’s an information about a Movie party where two of them were present.
Only efficient way is to manually break the query as “Find movies by Harrison Ford”, “Find movies by Steven Spielberg”. Now manually check the crew members in both the set and finally come up with the result “Indiana Jones”

2. Image search.
A user might be interested in searching for the pictures of Paris city. On Google image search if you type “Paris” you will get more results related to Paris Hilton than Paris city. The problem with the image search is more profound then with the regular search. The problem is because associating the photos with the keywords is much more difficult than simple looking for the keywords in the text of the documents. It’s very easy for the human to find out that the results are not correct (Paris Hilton and Paris city are different things) but the computer can do a visual verification of the results. Automatic image recognition is currently not a matured field.
The images that were shown basically correspond to the pages where the images were placed and the pages contained the keyword “Paris”.

3. Find new Music that I like

These kind of queries is at an even higher level of difficulty. From the perspective of automation, music retrieval is just as problematic as image search. The search engine can try to avoid the problem by not going into the content of the music but only get the clues of the performer or the genre from the web pages that have links to the music files. But there are some practical problems. The music is very fast moving so the content of the indexed pages might have changed. The search engines typically index the Web once a month and therefore too slow for the fast moving world of music releases.

The user can give the query like “Give me all the latest sad English songs” or “give me songs which are hip hop” so we are trying to query for songs from different artists and filter them on the type of song.

The search engine has no way to find out the content of the music and what is the meaning of the music.

Ideally a user would like that the search engine fetches the music related information from user’s online playlist that the user maintains and based on the type of songs the search engine can return them the latest songs.

4. Tell me about the music players with a capacity of at least 4 GB

So basically this is an ecommerce query. The user is looking for a product with certain characteristics.
The basic problem is that translating this query from natural language to the Boolean language of search engines is (almost) impossible. We could try the search “music player” “4GB” but it is clear that the search engine will not know that 4GB is the capacity of the music player and we are interested in all players with at least that much memory. The query will just return the pages containing the keywords as “music player” and 4GB. It cannot even make a choice if iPod, mp3 player should be considered as music player or not. In simple words if a web page is talking about a 4GB iPod, the page will not appear in the result set. The search engines don’t know what is a music player or a mp3 player. It is just a program capable of searching keywords from billions of pages across internet.

Also even if we somehow add modify the algorithm to make the search engines understand that iPod, mp3, mp4 are all kinds of music player the task of reading the web page to find out the capacity is quite tedious and erratic. The search engine will have to figure out where the information related to capacity has been mentioned. It has to parse the HTML page to find the information. Parsing the HTML page to find information cannot be generalized simply because every web page is created differently. Some html pages can have presentation information inside the page some can have a separate css file. Some of the HTML pages might be generating the information dynamically so the indexing is also not possible.
In short with the current search algorithm the query “give me all music players with a capacity of at least 4 GB “ is impossible to make

5. Tell me where I can find the cheapest iPad 16GB

The query is little different than the above since here the user has told specifically that he is looking for iPad 16 GB. So the search engine can go to Amazon, Google Froogle, ebay etc and get you the specific product. But the catch is the word “cheapest”
The user wants only the cheapest price. The search engine has to again parse the price related information. As discussed above the parsing of HTML pages for price information is very difficult. The price might be shown as “Total”, “Cost” etc. Also the various sites can give the value in different currency so 400$ < 380 euros but the search engine has no way to know this.


The above scenarios are the classic examples which indicate there is lot of scope for the improvement in the way search engine works.
In all the examples we are dealing with knowledge gap: What a computer understands and able to work with is much more limited than the knowledge of the user.
This lack of knowledge is mainly because of the technological difficulties in getting the computers to understand the natural language or to see the content of the image and the other multimedia.
If we can somehow provide the background information that the search engines can read, the above queries can be easily satisfied.

The semantic web is a concept to apply the advanced technologies in order to fill the gap between the human and the machine.

Without getting into the actual technologies of the semantic web, I will discuss about what can be the background information that can help the search engine to return the correct results.

1. In the first kind of query the user is basically looking for the information related to a person Frank van Harmelen. Some of the meta information (knowledge) that webpages can provide is
“Frank van Harmelen” is professor. He teaches at Vrije University. He has publication FVH98. He works-on “Semantic Web”.
Also the pages which were referring to Frank as “he” can add the meta information that “he” means Frank van Harmelen. The search engine won’t miss the pages that did not refer to him by the complete name.
Also if the search engine have some background information about the user who is tying the query (With the Google/ig , my yahoo the users can have a personalized search page), the user need not type “Frank van Harmelen Vrije university” “Frank Van Harmelen” should be sufficient.
Based on the user profile, his past web history, his online bookmarks, his homepage, the search engine can make some inferences that the user is interested in Semantic Web and that’s why he has typed “Frank Van Harmelen”. The search engine already knows that Frank van Harmelen works on Semantic Web, so the background information has completed the knowledge gap that previously existed.

There are ways to store the information in different forms like RDF, OWL which is out of scope of this article.

Similarly the movie based searches can be again enriched by maintaining some Meta information

Indiana Jones “is-a” Movie

Harrison Ford “acted-in” Indiana Jones

Steven Spielberg “directed” Indiana Jones


So the search engine knows that Harrison Ford and Steven Spielberg both are related to Indiana jones which is a movie. It can return the result as “Indiana Jones”. In this case the search engine can simply return the information as the name of the movie rather than the complete webpage. This is similar to typing “1USD to INR” on Google search page the result is the value 45.98. Google will find the value of the query expression automatically and display it. It’s kind of a calculator application

2. Image searches can be significantly improved by adding the tags describing them. Flickr actively supports tagging. Similarly the other sites which allow adding the images can have ask the users to add tags when they upload the images. The search engines can read these tags to understand the images. The images that are associated with a place, city, and country can be geo-coded. So the user can also query the images by clicking on the particular location on the map and ask for images of that place. The search engine can look at the geocodes of the indexed images and return them in the result
3. Media searches can again be improved by adding meta information about the music.
The meta information will cover the title of the music, the artists, type of music (sad, hip hop), release date etc. This meta information will allow the users to make the searched like
“Give me latest sad songs of XYZ artist”

If the user can maintain a online playlist, or specify the music preferences on the homepage, social networking profile the query can be made more powerful.
“Give me latest music”
Now the search engine knows the users taste and the information about the music. Based on this the search engine can return the correct results.

4. The e-commerce queries can be improved if the stores can maintain the information about the products in an open format which can be easily parsed by the search engines. So the information can say that iPod is of type music player, capacity 4GB, price 300, Currency: USD.
These days Amazon, ebay, Google base have provided a syntax that can be used by the stores (in case of Amazon) or the sellers (ebay, google base) to describe the products. Based on this information the search engines can execute the query “All music players of At least 4GB capacity”.
Since the format will specify very clearly the meaning of the fields, the search engines can be educated about it. Even if the format of each store is different we can write some kind of mappings between the fields. Amazon may call product as PRODUCT while ebay can call it ITEM.

5. The “cheapest iPad” query can be addressed by the above solution. The search engine can find out the prices in different stores by reading the XML tags. Also since the currency units are available. The conversion rates can be applied (read them dynamically from xe.com) and do the conversion

I have just scratched the surface of semantic web. It’s a vast research field with tremendous potential to improve the searching capabilities. Semantic web will certainly change the way the queries are written in the near future.

Sunday, May 31, 2009

"Big Bang Theory" and the technology





"Big Bang Theory" and the technology
The popular sitcom "Big Bang Theory" has become a means to promote the new technologies by making their characters talk about them. Some of the stuff that has been talked openly on the show is :
  1. Google Earth
  2. Google Street View
  3. Gmail
  4. Java applets
  5. Twitter
  6. Facebook
  7. Second Life
  8. MySpace
  9. Tivo
  10. iPod
  11. blog
  12. yelp
  13. iPhone
  14. twitter
  15. Mobile apps
  16. Android
  17. Kinect
  18. Siri
There has been an instance of the latest movie flick "Slumdog Millionaire" being discussed.
Feel free to add to the list if you find any thing that I am missing out





Saturday, August 2, 2008

My take on REST and SOAP

  1. Soap supports more RPC style of architecture where the use of SOAP is to invoke a remote function carrying in the message the function name and the various parameters. The RPC is basically a function that is sitting on a remote machine.
  2. The function has a specified number of parameters that needs to be provided to make use of the function. The use of SOAP is to make requests to such functions and to get the response back.
  3. SOAP uses XML to transfer the data and so it is heavy in size.
  4. The SOAP message is cryptic in the sense that it contains a header that wil specify the route, the info about the message and sometimes the security aspect for the message
  5. The SOAP message is difficult to create without the tools. So these days the langusgaes provide the library functions which will create the SOAP message
  6. The SOAP is generally sent using HTTP but other protocols are also valid like Java Message service
  7. SOAP is very function (verb ) centric. The way you get the things done is by calling a function so to get the stock prices you will call a function (web method: A webservice will have number of methods) getstock(GE)

Now the function will calculate the price and send it back to you

You must know the names of the function and the way it is going to use the parameters. For that you need to get the WSDL file which is very cryptic.

  1. SOAP syntax is not user friendly and human readable
  2. When SOAP makes the http request its difficult to find out which http method it is actually going to use.

REST

In case of rest the functions are fixed it will be get, put, post and delete. You will mention the name of the stock directly while making the request (each object will have a different URI) so www.stockprice/category/stock/GE

In this case the description of how to make the call is very simple and its intuitive.

No extra tool is required, The call is very simple.

REST is only for http since it uses the protocols methods GET, PUT(Update), POST (create), DELETE. This is good since the user don’t have to find out which method will be used for a specific purpose. Its basically service_name/noun so Stock is a service and GE is the noun

Saturday, April 19, 2008

How to create XMLListCollection from XML in flex 3

There are times when the data that you obtain is in the form of XML or a string that contains XML tags. For displaying the data in datagrid, list, trees we desire to convert the data in the XMLListCollection. We need to perform the following steps to get the XMLListCollection.

1. Lets assume that we want to convert the following string to the XMLListCollection

var xmlStr:String="<root>
<person>
<name>Rohit</name>
<surname>Agarwal</surname>
<phone>5551234</phone>
<age>24</age>
</person>
<person>
<name>Richa</name>
<surname>Mittal</surname>
<phone>5552341</phone>
<age>23</age>
</person>
<person>
<name>Puneet</name>
<surname>Jain</surname>
<phone>5553412</phone>
<age>23</age>
</person>
</root>";

2. Convert the string to XML

private var pat:XML ;

pat=new XML(xmlstr);

3. Convert the XML to XMLList. We want to have individual persons as seperate XML objects

private var patList:XMLList;
patList = pat.person;

4. Convert the XMLList to XMLListCollection

[Bindable]
private var patListCol:XMLListCollection;
patListCol = new XMLListCollection(patList);

In this way the XMLListCollection is created from the XML





How to convert a XML to ArrayCollection in Flex

I wanted to use AdvancedDataGrid control of Flex 3, for which the best way to represent data is in the form of an ArrayCollection. The problem was that the data available to me was in the form of an string(XML serialized as string) and not objects. So I wanted to convert the XML to ArrayCollection.

Steps
1. The following is the string that I wanted to convert:

var xmlStr:String="<root>
<person>
<name>Rohit</name>
<surname>Agarwal</surname>
<phone>5551234</phone>
<age>24</age>
</person>
<person>
<name>Richa</name>
<surname>Mittal</surname>
<phone>5552341</phone>
<age>23</age>
</person>
<person>
<name>Puneet</name>
<surname>Jain</surname>
<phone>5553412</phone>
<age>23</age>
</person>
</root>";

2. Convert the string to XMLDocument

var xmlDoc:XMLDocument = new XMLDocument(xmlStr);


3. Convert the XMLDocument to object by using SimpleXMLDecoder

var decoder:SimpleXMLDecoder = new SimpleXMLDecoder(true);
var resultObj:Object = decoder.decodeXML(xmlDoc);

4. Declare an ArrayCollection
[Bindable]
private var patArrayListCollection:ArrayCollection = new ArrayCollection();

5. Add the resultobj to the ArrayCollection

patArrayListCollection.addItem(resultObj.root.person);

The important thing to note here is the composition of the patArrayListCollection is in the form
[0] --main object
[0]-sub object 1
[1]-subobject 2
[2]-subobject 3

This is not in a form that we require to make it a data provider for the AdvancedDataGrid. The Grid requires the ArrayCollection to have
objects in the form
[0]-object 1
[1]-object 2
[2]-object 3


So to get this form the following step is done

6. var tempArray:ArrayCollection=patArrayListCollection.getItemAt(0)as ArrayCollection;

7. Finally assign tempArray to the AdvancedDataGrid
myADG.dataProvider=tempArray;






Sunday, April 13, 2008

ActionScript Error #2148:
SecurityError: Error #2148: SWF file file:///C:/Documents and Settings/UserProfile/Desktop/flexstore/bin-release/flexstore.swf cannot access local resource myFile.swf. Only local-with-filesystem and trusted local SWF files may access local resources.


This runtime error is thrown in Flex 3 if some where in the application you are trying to do a httpservice and use a resource from the local folder.
<mx:HTTPService id="fillTreeByCatRPC" url="categories.xml" resultFormat="e4x" />

I have seen this error only in Flex 3, Flex 2 never gave this error.

I did some google and found some solutions. Almost all the solutions suggests that one should change the flex compiler settings.

"add these arguments to the compiler (via Properties - Flex Compiler) : -use-network=false " http://curtismorley.com/2007/08/31/flash-cs3-flex-2-as3-error-2148/#comment-3714

The problem with this solution is that once the settings are changed then the application will not be able to read any remote resource. so the below request will fail
<mx:HTTPService id="fillTreeByCatRPC" url="http://www.resources.com/categories.xml" resultFormat="e4x" />

After doing further searches on Internet, I found that it is the setting problems of the flash player that cause the problem. Basically one needs to set the security settings of the flash player so that it allows the swf file to access the resources on the local system. This is done by visiting the following page
http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html

Make sure that the Global security settings are set to Always Allow

The following screenshot is what we are looking for
Once the settings has been done, Restart the browser and Flex 3 IDE

In all probability the error is gone.


Sunday, March 9, 2008

Customized event in Flex 2

Events are a way of sharing data between two components. Events also acts as a asynchronous message suggesting that some input has arrived to the receiver of the event. For e.g. when a person clicks on the button control the event click is generated signifying that a user input in the form of a click has occurred. Once the event has occurred we need to take some action like on button click display the “hello world” in a text box. The action that we take is known as handling of the event. Or in other words we need to specify the even handler. Event handler is a function that specifies what needs to be done on that particular event.

The following code snippet makes it clear

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx=="http://www.adobe.com/2006/mxml"

layout="vertical">

<mx:Script>

<![CDATA[

//Event handler for the button click function

private function buttonEventHandler(evt:Event):void{

taTest.text="Hello World";

}

]]>

</mx:Script>

<mx:Button id="btTest" label="Click Me" click="buttonEventHandler(event)" />

<mx:TextArea id="taTest" />

</mx:Application>


buttonEventHandler is the event handler that will be called when the button is clicked. One salient point to note is the argument passed in the handler. We pass the object of type Event i.e event. The object “event” is always available in the application and we need to use it at the time of calling an event handler.

Sometimes it happens that we need to transfer some data between the two components.

For e.g. there may be a component which is responsible to get the data from the server using a httprequestserver. Component populates the data in a collection and now wants to send to another component which implements the list or data grid to display the information to the end user. The events are the way through which this can be done. The catch here is that the event thrown by one component should be available in the other component. So the component1 when it is done with populating the collection will throw an event indicating which needs to be handled in the component2 responsible to display the collection in the datagrid. It happens because of the way the events are transmitted from the component to the Application. Before getting into the transmission concept we need to understand one more concept known as event listener. Event Listener signifies that the component wants to receive a particular event and so it wants to register itself as one of the recipients.

We use the function addEventListener(event name , event handler) to do that. Now you must be wondering that the above button code did not had any such function call then how were we able to handle the event. The simple answer is that the event that we talked about was provided by the flex framework and so every component has got an implicit event listener for such events.

But the events that we are now going to see are the one that user has created himself (customized events). The customized events are used to transfer the data. These are created by the users and so the components will not be aware of them. Event Listener explicitly registers the component to listen to these customized events.

HOW TO WRITE A CUSTOMIZED EVENT

There are 3 stages in order t use a customized event

1. Create customized event

2. Dispatch the customized event

3. Listen the customized event.

Create Stage

Let us see how we actually write a customized event. We are just discussing the salient points here which are required to write a customized event. Syntactical and theoretical details are well covered in the Adobe documents.

Customized event can be declared by writing a class that inherits from Event.

package controls

{

import flash.events.Event;

public class ItemAddedEvent extends Event

{

var itemDescription:String; //an item to be added to the cart

public static const ITEMADDEDEVENT:String ="ItemAddedEvent";

public function ItemAddedEvent(description:String)

{

super(ITEMADDEDEVENT,true,true);

itemDescription=description;

}

override public function clone():Event{

return new ItemAddedEvent(itemDescription);

}

}

}

These are the steps that need to follow for defining any customized event

1. The class has to extend Event

2. Declare what ever data type you want to transfer by this event.

var itemDescription:String; //an item to be added to the cart

3. One can give a name to the event for easy reference. In our case it is ITEMADDEDEVENT. We can give multiple names to the same event. This is required when we want to use the same event in different places. For e.g. in a shopping cart application we need to perform add item to cart, delete item from the cart and update the quantity of the item in the cart. In all the operations the same item type data is required to be passed. So we can define a single customized class that favors for the transfer of a item type data. But the same event class can be used for all the 3 functions. We will give 3 names so that we remember for what all purpose we are calling this class.

public static const ADD:String = "addtocart";

public static const REMOVE:String = "removefromcart";

public static const UPDATE:String = "updatecart";

4. In the Constructor we need to call super(). The parameters required to be passed are the type of the event (ADD,REMOVE,UPDATE) and the optional parameters specifying the properties of the event.

Super(type, isbubble,iscancellable)

The second argument signifies whether the event is allowed to bubble. i.e. an event thrown by a component is allowed to be listened by the components that are up in the hierarchy.

5. clone() . This is required as per the Adobe document. We need to override the clone function and in the body just instantiate the customized event and return the object so created.

override public function clone():Event

{

return new ItemAddedEvent(itemDescription);

}

That is all to be done for a creation of an event.

Dispatch stage:

The event is thrown by the component in this stage. There is a well defined procedure to be followed to do that.

Lets take an example and do that

<?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Metadata>

[Event(name="addItemEvent", type="controls.ItemAddedEvent")]

</mx:Metadata>

<mx:Label text="Item name:"/>

<mx:TextInput id="enteredItem"/>

<mx:Button width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]" label="Add Item" fontSize="12" click="greenClickEventHandler()"/>

<mx:Script>

<![CDATA[

import controls.ItemAddedEvent;

private function greenClickEventHandler():void{

trace("Ouch! I got clicked! Let me tell this to the world.");

// throws the event and the passes the string to the customized event object

dispatchEvent(new ItemAddedEvent(enteredItem.text)); // passing the string

}

]]>

</mx:Script>

In the example

<mx:Metadata>

[Event(name="addItemEvent", type="controls.ItemAddedEvent")]

</mx:Metadata>

The metadata section is an optional section that tells that these are the events this component is going to dispatch. It is more for giving the information to the developer that this particular code dispatches some event. This is useful since the other components by looking at the metadata section can find out the events they can listen to.

We give the name of the event (addItemEvent) and the location of the class (controls.ItemAddedEvent). Note we could have also given ITEMADDEDEVENT in place of addItemEvent.

private function greenClickEventHandler():void{

trace("Ouch! I got clicked! Let me tell this to the world.");

// throws the event and the passes the string to the customized event object

dispatchEvent(new ItemAddedEvent(enteredItem.text)); // passing the string

}

When the greenClickEventHandler() is getting called on the click event the component is calling the dispatchEvent function. By calling this function the component is actually throwing the customized event. The dispatchEvent function requires the object of the Customized event class as an argument. So essentially we have passed the data structure (in this case string) to the event. This data will be available to all the component who will listen to this event.

Listening

This is the process of registering for the event. The component has to explicitly tell the application that it wants to get the event thrown by the other component and handle the data that is also being passed along with the event. This is done with the help of addEventListener function. The next section will make this concept clearer. For now we can assume that the function allows the component to receive the event and then handle it.

For e.g.

Component called

addEventListener(ItemAddedEvent.ITEMADDEDEVENT,addItemtoCartEventHandler);

to register the event and tell which handler function to call

private function addItemtoCartEventHandler(event:ItemAddedEvent):void{

sample.text+="yes a book has been added"+ event.itemDescription;

}

In the event handler pass an object (event:ItemAddedEvent) of the customized event class type and then use the data passed through the event using the object passed in the argument.(event.itemDescription)

Now the final step is to instantiate the component that will generate the event which is

<controls:newlargebutton />

The way it will work is

Instantiate ----:comp1 will throw the customized event on click----: comp2 will listen to it and call its event handler

Now lets get into the intricacies of how the events are propagated between the components.

In Flex in order to use any component, that component must be instantiated in the application(the application tag).

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">

comp 1

comp 2

comp n

</mx:Application>

The Application is the root of all the components. So if make a hierarchy tree it will look like

<Application>

| |

<Comp1> <comp2>

So we can say that Application is the parent node of comp1 and comp2

Again there can be a situation where we instantiate a component inside another component. Like

<hbox>

<list>

<button>

<hbox>

so list and button are getting instantiated in hbox

so in these cases the hierarchy tree will look like

<Application>

|

<comp1>

|

<comp2>

But in this case also <application> is related to comp2 in a ancestral relationship.

We need to understand this point because of the nature of event propagation. When any component generates an event it can be listened by all the components that are higher in the hierarchy. So an event generated by comp2 can be listened by comp1 and the Application. This means comp1 can have an event listener to register for the event generated by comp2, similar is the case with Application.

So if comp2 has to send any data to comp1, it will simply generate an event which will send the data to the comp1 which would be listening for this event.

There may be a situation where the components are not in the direct hierarchy but are in a sibling relation

<Application>

| |

<comp1> <comp2>

Now an event produced by comp2 will be easily listened by Application, but not by the comp1. But comp2 wanted to make comp1 listen to the event. Now events that are listened by the parent can be listened by the children also through following command

parent.addEventListener(event type,event handler)

This means that comp1 can listen to the events that reaches upto the parent. So the event sent by comp2 reaches Appication. Now this event can be heard by the comp1.

So in order to pass the events from one component to another one has to look at the way they are related to each other and depending on that call the addEventListener().

Lets look at some of the examples for understanding the concepts

E.g.1 There are two components related to each other in a parent child relationship. Comp1: It’s a VBOX containing a button and a textbox.

Comp2: A VBOX containing TextArea

Now the requirement is that in comp1 what ever is entered in textbox should be displayed in Comp2 textarea on the button click. So basically we want to send text string from comp1 to comp2. This is a classical situation where we will write a customized event to transfer the string between the two components.

The way we have arranged the components in the implementation is

<Application>

|

<comp2>

|

<comp1>

so addeventlistener will be called without parent prefix in comp1

Custom Event class (ItemAddedEvent.as)

package controls

{

import flash.events.Event;

public class ItemAddedEvent extends Event

{

var itemDescription:String; //an item to be added to the cart

public static const ITEMADDEDEVENT:String ="ItemAddedEvent";

public function ItemAddedEvent(description:String)

{

super(ITEMADDEDEVENT,true,true);

itemDescription=description;

}

override public function clone():Event{

return new ItemAddedEvent(itemDescription);

}

}

}

Comp1 (newlargebutton.mxml)

<?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Metadata>

[Event(name="addItemEvent", type="controls.ItemAddedEvent")]

</mx:Metadata>

<mx:Label text="Item name:"/>

<mx:TextInput id="enteredItem"/>

<mx:Button width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]" label="Add Item" fontSize="12" click="greenClickEventHandler()"/>

<mx:Script>

<![CDATA[

import controls.ItemAddedEvent;

private function greenClickEventHandler():void{

trace("Ouch! I got clicked! Let me tell this to the world.");

// throws the event and the passes the string to the customized event object

dispatchEvent(new ItemAddedEvent(enteredItem.text)); // passing the string

}

]]>

</mx:Script>

</mx:VBox>

Comp2: (BlindShoppingCart.mxml)

<?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"

xmlns:controls="controls.*"

creationComplete="init()">

<mx:Script>

<![CDATA[

import flash.events.Event;

import controls.ItemAddedEvent;

private function init():void

{

// eventlistener

addEventListener(ItemAddedEvent.ITEMADDEDEVENT,addItemtoCartEventHandler);

}

private function addItemtoCartEventHandler(event:ItemAddedEvent):void{

sample.text+="yes a book has been added"+ event.itemDescription;

}

]]>

</mx:Script>

<!—instantiated the comp1 -- >

<controls:newlargebutton addItemEvent="addItemtoCartEventHandler(event)" />

<mx:TextArea id="sample" />

</mx:VBox>

Application (greenbutton.mxml)

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical"

xmlns:ctrl="controls.*" >

<ctrl:BlindShoppingCart width="350" height="200" />

</mx:Application>



Same example but instead of child parent relation change it to sibling

So the instantiation of the comp1 will not happen inside comp2 instead it will happen in the Apllication

<Application>

| |

<comp1> <comp2>

Custom Event class (ItemAddedEvent.as)

package controls

{

import flash.events.Event;

public class ItemAddedEvent extends Event

{

var itemDescription:String; //an item to be added to the cart

public static const ITEMADDEDEVENT:String ="ItemAddedEvent";

public function ItemAddedEvent(description:String)

{

super(ITEMADDEDEVENT,true,true);

itemDescription=description;

}

override public function clone():Event{

return new ItemAddedEvent(itemDescription);

}

}

}

Comp1 (newlargebutton.mxml)

<?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml">

<mx:Metadata>

[Event(name="addItemEvent", type="controls.ItemAddedEvent")]

</mx:Metadata>

<mx:Label text="Item name:"/>

<mx:TextInput id="enteredItem"/>

<mx:Button width="104" height="28" cornerRadius="10" fillColors="[#00ff00, #00B000]" label="Add Item" fontSize="12"

click="greenClickEventHandler()"/>

<mx:Script>

<![CDATA[

import controls.ItemAddedEvent;

private function greenClickEventHandler():void{

trace("Ouch! I got clicked! Let me tell this to the world.");

// throws the event and the passes the string to the customized event object

dispatchEvent(new ItemAddedEvent(enteredItem.text)); // passing the string

}

]]>

</mx:Script>

</mx:VBox>

Comp2: (BlindShoppingCart.mxml)

<?xml version="1.0" encoding="utf-8"?>

<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:controls="controls.*"

creationComplete="init()">

<mx:Script>

<![CDATA[

import flash.events.Event;

import controls.ItemAddedEvent;

private function init():void

{

// eventlistener

//addEventListener(ItemAddedEvent.ITEMADDEDEVENT,addItemtoCartEventHandler); --wont work

parent.addEventListener(ItemAddedEvent.ITEMADDEDEVENT,addItemtoCartEventHandler);

}

private function addItemtoCartEventHandler(event:ItemAddedEvent):void{

sample.text+="yes a book has been added"+ event.itemDescription;

}

]]>

</mx:Script>

<mx:TextArea id="sample" />

</mx:VBox>

Application (greenbutton.mxml)

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

layout="vertical" xmlns:ctrl="controls.*" >

<ctrl:newlargebutton width="350" height="82" />

<ctrl:BlindShoppingCart width="350" />

</mx:Application>

In case the parent.addeventListener is not given , the event is not dispatched to the comp2 and so on button click the text in the text are is not written.



Since in the example we have given parent.addeventListener, so comp1 and interact to comp2 via parent and we get