Pages

Wednesday, 28 March 2012

Shared Objects in Flex - Like cookies in the Browsers

Introduction:

Shared objects are like browser cookies however
  • They do not expire by default.
  • By default, they are limited to a size of 100 KB each.
  • They can store simple data types (such as String, Array, and Date).
  • They are stored in a location specified by the application (within the user's home directory).
  • They are never transmitted between the client and server.
  • Use getLocal() to create a shared object. (SharedObject.getLocal("myTasks"); )
  • Use flush() to write the shared object to the client file. (sharedObj.flush())
  • Use clear() to destroy a shared object (sharedObj.clear())

SharedObjectExample.MXML

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
 layout="absolute"
 creationComplete="initSharedObject()">
 <mx:Script>
  <![CDATA[
  import flash.net.SharedObject;

  public var sharedObj:SharedObject;

   private function initSharedObject():void{
   sharedObj = SharedObject.getLocal("myTasks");
      if (sharedObj.size > 0)
       textareaTasks.text=sharedObj.data.tasks;
  }

   public function localconnectionHandler(msg:String):void {
   textareaTasks.text= textareaTasks.text + msg + "\n";
     }

     private function clearTasks(event:MouseEvent):void {
         textareaTasks.text="";
     }

     private function saveTasks(event:MouseEvent):void {
         sharedObj.data.tasks = textareaTasks.text;
   sharedObj.flush();
     }

  private function deleteSavedTasks(event:MouseEvent):void {
      sharedObj.clear();
  }

  ]]>
 </mx:Script>
 <mx:Panel  horizontalCenter="0" verticalCenter="0.5" verticalGap="15"
   paddingLeft="20" paddingRight="20" paddingBottom="20" 
                 paddingTop="20"  height="300">
  <mx:Label text="Your tasks are..."/>
  <mx:TextArea id="textareaTasks"
    top="20" left="20" right="20" bottom="20"
    width="100%" height="100%"/>
  <mx:HBox>
   <mx:Button id="btnClearTasks" click="clearTasks(event)"
    label="Clear Tasks"/>
   <mx:Button id="btnSaveTasks" click="saveTasks(event)"
    label="Save Tasks to Shared Object"/>
   <mx:Button id="btnDeleteSavedTasks" 
                                click="deleteSavedTasks(event)"
    label="Delete Saved Shared Object Tasks"/>
  </mx:HBox>
 </mx:Panel>
</mx:Application>

 Output Screen:

You can store the content into the shared object by giving input through the text box. The stored content will not expire by default theay will be available after u refresh the page unless you clear that by using Clear() call. 

No comments:

Post a Comment