Shared Objects in Flex

January 24, 2008

It will be value add to your web applications if they can recognize the users who are revisiting your applications and displays customized messages to the user. Adobe Flex provides a good solution for this. Adobe Flex allows developers to store objects on the client’s machine without compromising security on the client’s machine.

What are Shared Objects

Shared objects behave like cookies. You use SharedObject class to store data on the client’s hard disk and retrieve those objects in the same session or in another session. Applications can access their own shared object data only. You can make your shared data object available to other application from the same domain and you cannot share with applications from other domains.

Shared objects allow you to write simple objects like Arrays, String and Date. You can create multiple shared objects for one application. Each shared object is associated with a name. To add data to shared objects, you use the data property of the shared object. Below is a function, which display a welcome message if the user is revisiting.

By default, Flash can save locally persistent SharedObject objects of up to 100 KB per domain. When the application tries to save data to a shared object that would make it bigger than 100 KB, Flash Player displays the Local Storage dialog box, which lets the user allow or deny local storage for the domain that is requesting access.

1 private function storeVisitDate():void

2 {

3 var visitDate:SharedObject = SharedObject.getLocal(“userVisitedDate”);

4 if(visitDate.data.lastVisitedDate != null)

5 {

6 Alert.show(“Welcome back, you visited last on ” + visitDate.data.lastVisitedDate);

7 }

8 visitDate.data.lastVisitedDate = new Date();

9 visitDate.flush();

10 }

Explanation:

Line #3: getLocal() method of the shared object retrieves shared object with the name specified. If the object does not exist it is created.

Line #4: checking if lastVisitedDate property is available. If it is available then we retrieve it.

Line#8 and #9: here we reset the lastVisitedDate property and use flush() method to save the shared object. Invoking flush() method is not necessary, shared objects are automatically saved when the application is closed.

Please refer to SharedObject in Flex language reference for more details.