View comments | RSS feed
Packageflash.net
Classpublic class SharedObject
InheritanceSharedObject Inheritance EventDispatcher Inheritance Object

The SharedObject class is used to read and store limited amounts of data on a user's computer or on a server. Shared objects offer real-time data sharing between multiple client SWF files and objects that are persistent on the local computer or remote server. Local shared objects are similar to browser cookies and remote shared objects are similar to real-time data transfer devices. To use remote shared objects, you need a server, such as Adobe Flex or Adobe's Macromedia Flash Media Server 2.

Some of the properties and methods in the NetStream class are intended for use primarily with a server, such as Flash Media Server 2 or Flex. They may contain additional server-side functionality. For additional documentation, see the NetStream class in Flash Media Server documentation.

Three common uses of shared objects are described below:

To create a local shared object, use the following syntax:

 var so:SharedObject = SharedObject.getLocal("userHighScore");
 so.data.highScore = new Number(1234567890);
 so.flush();
 

In the example, the shared object is explicitly flushed, or written to a disk. When an application closes, shared objects are automatically flushed; however, flushing is shown here to demonstrate the step of writing data to a disk.

Local disk space considerations: Local shared objects can be very useful, but they have some limitations that are important to consider as you design your application. Sometimes your SWF files may not be allowed to write local shared objects, and sometimes the data stored in local shared objects can be deleted without your knowledge. Flash Player users can manage the disk space that is available to individual domains or to all domains. When users decrease the amount of disk space available, some local shared objects may be deleted. Flash Player users also have privacy controls that can prevent third-party domains (domains other than the domain in the current browser address bar) from reading or writing local shared objects.

Note: SWF files that are stored and run on the local computer, not from a remote server, can always write third-party shared objects to disk, even if the user does not allow writing of shared objects to disk by third-party domains. For more information about third-party shared objects, see the discussion about third-party content on the Global Storage Settings panel in Flash Player Help.

Adobe recommends that you check for failures that are related to the amount of disk space and to user privacy controls. Perform these checks when you call getLocal() and flush():

If your SWF file attempts to create or modify local shared objects, make sure that your SWF file is at least 215 pixels wide and at least 138 pixels high (the minimum dimensions for displaying the dialog box that prompts users to increase their local shared object storage limit). If your SWF file is smaller than these dimensions and an increase in the storage limit is required, SharedObject.flush() fails, returning SharedObjectFlushedStatus.PENDING and dispatching the netStatus event.

View the examples.

See also

flush()
getLocal()
netStatus


Public Properties
 PropertyDefined by
  client : Object
Indicates the object on which callback methods are invoked.
SharedObject
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  data : Object
[read-only] The collection of attributes assigned to the data property of the object; these attributes can be shared and stored.
SharedObject
  defaultObjectEncoding : uint
[static] The default object encoding (AMF version) for all local shared objects created in the SWF file.
SharedObject
  fps : Number
[write-only] Specifies the number of times per second that a client's changes to a shared object are sent to the server.
SharedObject
  objectEncoding : uint
The object encoding (AMF version) for this shared object.
SharedObject
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
  size : uint
[read-only] The current size of the shared object, in bytes.
SharedObject
Public Methods
 MethodDefined by
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
  
For local shared objects, purges all of the data and deletes the shared object from the disk.
SharedObject
  
Closes the connection between a remote shared object and the server.
SharedObject
  
connect(myConnection:NetConnection, params:String = null):void
Connects to a remote shared object on the server through the specified connection.
SharedObject
 Inherited
Dispatches an event into the event flow.
EventDispatcher
  
flush(minDiskSpace:int = 0):String
Immediately writes a locally persistent shared object to a local file.
SharedObject
  
getLocal(name:String, localPath:String = null, secure:Boolean = false):SharedObject
[static] Returns a reference to a locally persistent shared object that is available only to the current client.
SharedObject
  
getRemote(name:String, remotePath:String = null, persistence:Object = false, secure:Boolean = false):SharedObject
[static] Returns a reference to an object that can be shared across multiple clients by means of a server, such as Flash Media Server.
SharedObject
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
send(... arguments):void
Broadcasts a message to all clients connected to the specified remote shared object, including the client that sent the message.
SharedObject
  
setDirty(propertyName:String):void
Indicates to the server that the value of a property (defined with the data property) in the shared object has changed.
SharedObject
  
setProperty(propertyName:String, value:Object = null):void
Updates the value of a property (defined with the data property) in a shared object and indicates to the server that the value of the property has changed.
SharedObject
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 EventSummaryDefined by
 Inherited Dispatched when Flash Player gains operating system focus and becomes active.EventDispatcher
   Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code.SharedObject
 Inherited Dispatched when Flash Player loses operating system focus and is becoming inactive.EventDispatcher
   Dispatched when a SharedObject instance is reporting its status or error condition.SharedObject
   Dispatched when a remote shared object (SharedObject) has been updated by the server.SharedObject
Property detail
clientproperty
client:Object  [read-write]

Indicates the object on which callback methods are invoked. The default object is this. You can set the client property to another object, and callback methods will be invoked on that other object.

Implementation
    public function get client():Object
    public function set client(value:Object):void

Throws
TypeError — The client property must be set to a non-null object.
dataproperty 
data:Object  [read-only]

The collection of attributes assigned to the data property of the object; these attributes can be shared and stored. Each attribute can be an object of any ActionScript or JavaScript type — Array, Number, Boolean, ByteArray, XML, and so on. For example, the following lines assign values to various aspects of a shared object:

  var items_array:Array = new Array(101, 346, 483);
  var currentUserIsAdmin:Boolean = true;
  var currentUserName:String = "Ramona";
  
  var my_so:SharedObject = SharedObject.getLocal("superfoo");
  my_so.data.itemNumbers = items_array;
  my_so.data.adminPrivileges = currentUserIsAdmin;
  my_so.data.userName = currentUserName;
  
  for (var prop in my_so.data) {
    trace(prop+": "+my_so.data[prop]);
  }
  

All attributes of a shared object's data property are saved if the object is persistent, and the shared object contains the following information:

  userName: Ramona
  adminPrivileges: true
  itemNumbers: 101,346,483
  

Note: Do not assign values directly to the data property of a shared object, as in so.data = someValue; Flash Player ignores these assignments.

To delete attributes for local shared objects, use code such as delete so.data.attributeName; setting an attribute to null or undefined for a local shared object does not delete the attribute.

To create private values for a shared object — values that are available only to the client instance while the object is in use and are not stored with the object when it is closed — create properties that are not named data to store them, as shown in the following example:

  var my_so:SharedObject = SharedObject.getLocal("superfoo");
  my_so.favoriteColor = "blue";
  my_so.favoriteNightClub = "The Bluenote Tavern";
  my_so.favoriteSong = "My World is Blue";
  
  for (var prop in my_so) {
    trace(prop+": "+my_so[prop]);
  }
  

The shared object contains the following data:

  favoriteSong: My World is Blue
  favoriteNightClub: The Bluenote Tavern
  favoriteColor: blue
  data: [object Object]
  
Implementation
    public function get data():Object

See also

defaultObjectEncodingproperty 
defaultObjectEncoding:uint  [read-write]

The default object encoding (AMF version) for all local shared objects created in the SWF file. When local shared objects are written to disk, the SharedObject.defaultObjectEncoding property indicates which Action Message Format version should be used: the ActionScript 3.0 format (AMF3) or the ActionScript 1.0 or 2.0 format (AMF0).

For more information about object encoding, including the difference between encoding in local and remote shared objects, see the description of the objectEncoding property.

The default value of SharedObject.defaultObjectEncoding is set to use the ActionScript 3.0 format, AMF3. If you need to write local shared objects that ActionScript 2.0 or 1.0 SWF files can read, set SharedObject.defaultObjectEncoding to use the ActionScript 1.0 or ActionScript 2.0 format, flash.net.ObjectEncoding.AMF0, at the beginning of your script, before you create any local shared objects. All local shared objects created thereafter will use AMF0 encoding and can interact with older content. You cannot change the objectEncoding value of existing local shared objects by setting SharedObject.defaultObjectEncoding after the local shared objects have been created.

To set the object encoding on a per-object basis, rather than for all shared objects created by the SWF file, set the objectEncoding property of the local shared object instead.

Implementation
    public static function get defaultObjectEncoding():uint
    public function set defaultObjectEncoding(value:uint):void

See also

fpsproperty 
fps:Number  [write-only]

Specifies the number of times per second that a client's changes to a shared object are sent to the server.

Use this method when you want to control the amount of traffic between the client and the server. For example, if the connection between the client and server is relatively slow, you may want to set fps to a relatively low value. Conversely, if the client is connected to a multiuser application in which timing is important, you may want to set fps to a relatively high value.

Setting fps will trigger a sync event and update all changes to the server. If you only want to update the server manually, set fps to 0.

Changes are not sent to the server until the sync event has been dispatched. That is, if the response time from the server is slow, updates may be sent to the server less frequently than the value specified in this property.

Implementation
    public function set fps(value:Number):void
objectEncodingproperty 
objectEncoding:uint  [read-write]

The object encoding (AMF version) for this shared object. When a local shared object is written to disk, the objectEncoding property indicates which Action Message Format version should be used: the ActionScript 3.0 format (AMF3) or the ActionScript 1.0 or 2.0 format (AMF0).

Object encoding is handled differently depending if the shared object is local or remote.

Implementation
    public function get objectEncoding():uint
    public function set objectEncoding(value:uint):void

Throws
ReferenceError — You attempted to set the value of the objectEncoding property on a remote shared object. This property is read-only for remote shared objects because its value is determined by the associated NetConnection instance.

See also

sizeproperty 
size:uint  [read-only]

The current size of the shared object, in bytes.

Flash calculates the size of a shared object by stepping through all of its data properties; the more data properties the object has, the longer it takes to estimate its size. Estimating object size can take significant processing time, so you may want to avoid using this method unless you have a specific need for it.

Implementation
    public function get size():uint

See also


Example
The following code creates a SharedObject object using an id "thehobbit". A property named username is added to the data property of the SharedObject object. The size property is then traced, which returns the value indicated.

import flash.net.SharedObject;

// if these get copied or not
var mySo:SharedObject = SharedObject.getLocal("thehobbit");
mySo.data.username = "bilbobaggins";
trace(mySo.size); // 55

Method detail
clear()method
public function clear():void

For local shared objects, purges all of the data and deletes the shared object from the disk. The reference to the shared object is still active, but its data properties are deleted.

For remote shared objects, this method disconnects the object and purges all of the data; if the shared object is locally persistent, the method also deletes the shared object from the disk. The reference to the shared object is still active, but its data properties are deleted.


Example
The following code creates (and on subsequent executions, retrieves) a SharedObject object using an id with the value of hostName. A property named username is added to the data property of the SharedObject object. The clear() method is finally called, which wipes out all information that was added to the data object (in this case was a single property named username).

package {
    import flash.net.SharedObject;

    public class SharedObject_clear {
        private var hostName:String = "yourDomain";
        private var username:String = "yourUsername";

        public function SharedObject_clear() {
            var mySo:SharedObject = SharedObject.getLocal(hostName);
            if(mySo.data.username == null) {
                mySo.data.username = username;
                trace("set: " + mySo.data.username); // yourUsername
            }
            else {
                mySo.clear();
                trace("cleared: " + mySo.data.username); // undefined
            }
        }
    }
}

close()method 
public function close():void

Closes the connection between a remote shared object and the server. If a remote shared object is locally persistent, the user can make changes to the local copy of the object after this method is called. Any changes made to the local object are sent to the server the next time the user connects to the remote shared object.

connect()method 
public function connect(myConnection:NetConnection, params:String = null):void

Connects to a remote shared object on the server through the specified connection. Use this method after issuing SharedObject.getRemote(). After a successful connection, the sync event is dispatched.

Before attempting to work with a remote shared object, first check for a return value of true, indicating a successful connection, and then wait until the sync event is dispatched. If you fail to do so, any changes you make to the object locally — before the sync event is dispatched — may be lost.

Note: The sync event is not dispatched if this call returns false.

Parameters
myConnection:NetConnection — A NetConnection object (such as one used to communicate with Flash Media Server) that is using the Real-Time Messaging Protocol (RTMP).
 
params:String (default = null)

Throws
Error — Flash Player could not connect to the specified remote shared object. Verify that the NetConnection instance is valid and connected and that the remote shared object was successfully created on the server.

See also

flush()method 
public function flush(minDiskSpace:int = 0):String

Immediately writes a locally persistent shared object to a local file. If you don't use this method, Flash Player writes the shared object to a file when the shared object session ends — that is, when the SWF file is closed, when the shared object is garbage-collected because it no longer has any references to it, or when you call SharedObject.clear() or SharedObject.close().

If this method returns SharedObjectFlushStatus.PENDING, Flash Player displays a dialog box asking the user to increase the amount of disk space available to objects from this domain. To allow space for the shared object to grow when it is saved in the future, which avoids return values of PENDING, pass a value for minDiskSpace. When Flash Player tries to write the file, it looks for the number of bytes passed to minDiskSpace, instead of looking for enough space to save the shared object at its current size.

For example, if you expect a shared object to grow to a maximum size of 500 bytes, even though it might start out much smaller, pass 500 for minDiskSpace. If Flash asks the user to allot disk space for the shared object, it asks for 500 bytes. After the user allots the requested amount of space, Flash won't have to ask for more space on future attempts to flush the object (as long as its size doesn't exceed 500 bytes).

After the user responds to the dialog box, this method is called again and the netStatus event is dispatched with a code property of SharedObject.Flush.Success or SharedObject.Flush.Failed.

Parameters
minDiskSpace:int (default = 0) — The minimum disk space, in bytes, that must be allotted for this object.

Returns
String — Either of the following values:
  • SharedObjectFlushStatus.PENDING: The user has permitted local information storage for objects from this domain, but the amount of space allotted is not sufficient to store the object. Flash Player prompts the user to allow more space.
  • SharedObjectFlushStatus.FLUSHED: The shared object has been successfully written to a file on the local disk.

Throws
Error — Flash Player cannot write the shared object to disk. This error might occur if the user has permanently disallowed local information storage for objects from this domain.

Note: Local content can always write shared objects from third-party domains (domains other than the domain in the current browser address bar) to disk, even if writing of third-party shared objects to disk is disallowed.

See also


Example
The following code creates (and on subsequent executions, retrieves) a SharedObject object using an id with the value of hostName. A property named username is added to the data property of the SharedObject object. The flush() method is then called, followed by a check to see if the string pending, or a boolean value of true or false was returned. One should be aware that all open SharedObject instances will automatically be flushed whenever the current instance of the Flash Player is closed.
package {
    import flash.net.SharedObject;

    public class SharedObject_flush {
        private var hostName:String = "yourDomain";
        private var username:String = "yourUsername";

        public function SharedObject_flush() {
            var mySo:SharedObject = SharedObject.getLocal(hostName);
            mySo.data.username = username;
            var flushResult:Object = mySo.flush();
            trace("flushResult: " + flushResult);
            trace(mySo.data.username); // yourUsername
        }
    }
}

getLocal()method 
public static function getLocal(name:String, localPath:String = null, secure:Boolean = false):SharedObject

Returns a reference to a locally persistent shared object that is available only to the current client. If the shared object does not already exist, this method creates one. If any values passed to getLocal() are invalid or if the call fails, Flash Player throws an exception.

The following code shows how you assign the returned shared object reference to a variable:

var so:SharedObject = SharedObject.getLocal("savedData");

Note: If the user has chosen to never allow local storage for this domain, the object is not saved locally, even if a value for localPath is specified. The exception to this rule is local content. Local content can always write shared objects from third-party domains (domains other than the domain in the current browser address bar) to disk, even if writing of third-party shared objects to disk is disallowed.

To avoid name conflicts, Flash looks at the location of the SWF file that is creating the shared object. For example, if a SWF file at www.myCompany.com/apps/stockwatcher.swf creates a shared object named portfolio, that shared object does not conflict with another object named portfolio that was created by a SWF file at www.yourCompany.com/photoshoot.swf because the SWF files originate from different directories.

Although the localPath parameter is optional, you should give some thought to its use, especially if other SWF files need to access the shared object. If the data in the shared object is specific to one SWF file that will not be moved to another location, then use of the default value makes sense. If other SWF files need access to the shared object, or if the SWF file that creates the shared object will later be moved, then the value of this parameter affects how accessible the shared object will be. For example, if you create a shared object with localPath set to the default value of the full path to the SWF file, no other SWF file can access that shared object. If you later move the original SWF file to another location, not even that SWF file can access the data already stored in the shared object.

To avoid inadvertently restricting access to a shared object, use the localpath parameter. The most permissive approach is to set localPath to / (slash), which makes the shared object available to all SWF files in the domain, but increases the likelihood of name conflicts with other shared objects in the domain. A more restrictive approach is to append localPath with folder names that are in the full path to the SWF file. For example, for a portfolio shared object created by the SWF file at www.myCompany.com/apps/stockwatcher.swf, you could set the localPath parameter to /, /apps, or /apps/stockwatcher.swf. You must determine which approach provides optimal flexibility for your application.

When using this method, consider the Flash Player security model:

Suppose you publish SWF file content to be played back as local files (either locally installed SWF files or EXE files), and you need to access a specific shared object from more than one local SWF file. In this situation, be aware that for local files, two different locations might be used to store shared objects. The domain that is used depends on the security permissions granted to the local file that created the shared object. Local files can have three different levels of permissions:

  1. Access to the local filesystem only.
  2. Access to the network only.
  3. Access to both the network and the local filesystem.

Local files with access to the local filesystem (level 1 or 3) store their shared objects in one location. Local files without access to the local filesystem (level 2) store their shared objects in another location.

You can prevent a SWF file from using this method by setting the allowNetworking parameter of the the object and embed tags in the HTML page that contains the SWF content.

For more information, see the following:

Parameters
name:String — The name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:
  ~ % & \ ; : " ' , < > ? # 
  
 
localPath:String (default = null) — The full or partial path to the SWF file that created the shared object, and that determines where the shared object will be stored locally. If you do not specify this parameter, the full path is used.
 
secure:Boolean (default = false) — Determines whether access to this shared object is restricted to SWF files that are delivered over an HTTPS connection. If your SWF file is delivered over HTTPS, this parameter's value has the following effects:
  • If this parameter is set to true, Flash Player creates a new secure shared object or gets a reference to an existing secure shared object. This secure shared object can be read from or written to only by SWF files delivered over HTTPS that call SharedObject.getLocal() with the secure parameter set to true.
  • If this parameter is set to false, Flash Player creates a new shared object or gets a reference to an existing shared object that can be read from or written to by SWF files delivered over non-HTTPS connections.

If your SWF file is delivered over a non-HTTPS connection and you try to set this parameter to true, the creation of a new shared object (or the access of a previously created secure shared object) fails and null is returned. Regardless of the value of this parameter, the created shared objects count toward the total amount of disk space allowed for a domain.

The following diagram shows the use of the secure parameter:

secure shared object diagram

Returns
SharedObject — A reference to a shared object that is persistent locally and is available only to the current client. If Flash Player can't create or find the shared object (for example, if localPath was specified but no such directory exists), this method throws an exception.

Throws
Error — Flash Player cannot create the shared object for whatever reason. This error might occur is if persistent shared object creation and storage by third-party Flash content is prohibited (does not apply to local content). Users can prohibit third-party persistent shared objects on the Global Storage Settings panel of the Settings Manager, located at http://www.adobe.com/support/documentation/en/flashplayer/help/settings_manager03.html.

See also

getRemote()method 
public static function getRemote(name:String, remotePath:String = null, persistence:Object = false, secure:Boolean = false):SharedObject

Returns a reference to an object that can be shared across multiple clients by means of a server, such as Flash Media Server. If the shared object does not already exist, this method creates one.

The following code shows how you assign the returned shared object reference to a variable:

var myRemote_so:SharedObject = SharedObject.getRemote(name, remotePath, persistence);

To create a shared object that is available only to the current client, use SharedObject.getLocal().

After calling this method, use SharedObject.connect() to connect the object to the application server, as shown in the following code:

     var myNC:NetConnection = new NetConnection();
     myNC.connect("rtmp://[yourDomain].com/applicationName");
     var myRemoteSO:SharedObject = SharedObject.getRemote("mo", myNC.uri, false);
     myRemoteSO.connect(myNC);
     

To confirm that the local and remote copies of the shared object are synchronized, use the sync event.

All clients that want to share this object must pass the same values for the name and remotePath parameters. For additional information about remote shared objects, see SharedObject.getRemote() in the Flash Media Server documentation.

Parameters
name:String — The name of the object. The name can include forward slashes (/); for example, work/addresses is a legal name. Spaces are not allowed in a shared object name, nor are the following characters:
 ~ % & \ ; :  " ' , > ? ? #
 
remotePath:String (default = null) — The URI of the server on which the shared object will be stored. This URI must be identical to the URI of the NetConnection object passed to the SharedObject.connect() method.
 
persistence:Object (default = false) — Specifies whether the attributes of the shared object's data property are persistent locally, remotely, or both. This parameter can also specify where the shared object will be stored locally. Acceptable values are as follows:
  • A value of false specifies that the shared object is not persistent on the client or server.
  • A value of true specifies that the shared object is persistent only on the server.
  • A full or partial local path to the shared object indicates that the shared object is persistent on the client and the server. On the client, it is stored in the specified path; on the server, it is stored in a subdirectory within the application directory.

Note: If the user has chosen to never allow local storage for this domain, the object will not be saved locally, even if a local path is specified for persistence. For more information, see the class description.

 
secure:Boolean (default = false) — Determines whether access to this shared object is restricted to SWF files that are delivered over an HTTPS connection. For more information, see the description of the secure parameter in the getLocal method entry.

Returns
SharedObject — A reference to an object that can be shared across multiple clients.

Throws
Error — Flash Player can't create or find the shared object. This might occur if nonexistent paths were specified for the remotePath and persistence parameters.

See also

send()method 
public function send(... arguments):void

Broadcasts a message to all clients connected to the specified remote shared object, including the client that sent the message. To process and respond to the message, create a handler function to send to the shared object.

Parameters
... arguments — One or more arguments: A string that identifies the message; the name of one or more handler functions to attach to the shared object; and optional parameters that can be of any type. They are serialized and sent over the connection, and the receiving handler receives them in the same order. If a parameter is a circular object (for example, a linked list that is circular), the serializer handles the references correctly.

Note: Do not use a reserved term for the function names. For example, myRemoteSO.send("close") will fail.

setDirty()method 
public function setDirty(propertyName:String):void

Indicates to the server that the value of a property (defined with the data property) in the shared object has changed. This method marks properties as changed (dirty) and is used in server-side ActionScript.

You create properties for a shared object using the SharedObject.data property or simply by creating new, uniquely named SharedObject properties. For more information about the difference between these two techniques, see the SharedObject.data property.

The SharedObject.setProperty() method implements the setDirty() method. In most cases, such as when the value of a property is a primitive type like String or Number, you would use setProperty() instead of setDirty(). However, when the value of a property is an object that contains its own properties, use setDirty() to indicate when a value within the object has changed.

Parameters
propertyName:String — The name of the property that has changed.

See also

setProperty()method 
public function setProperty(propertyName:String, value:Object = null):void

Updates the value of a property (defined with the data property) in a shared object and indicates to the server that the value of the property has changed. The setProperty() method explicitly marks properties as changed (dirty) and is used in server-side ActionScript. Some servers, such as Flash Media Server, require an explicit call to setProperty() to indicate when a property of the shared object has changed.

If you call SharedObject.setProperty() on the server side, it invokes a change notification through the sync event on the client side for any Flash Player client that is using the shared object. The propertyName parameter on the server side is the same as an attribute of the data property on the client side. For example, the following lines of code are all equivalent: the first two lines are server-side ActionScript, and the third and fourth are client-side ActionScript:

  setProperty("nameVal", "foo");
  setDirty("nameVal");
  data["nameVal"] = "foo";
  data.nameVal = "foo";
  

Users of Flash Media Server can find additional information on server-side ActionScript and remote shared objects in the Flash Media Server Server-Side ActionScript Language Reference.

Note: The SharedObject.setProperty() method implements the setDirty() method. In most cases, such as when the value of a property is a primitive type like String or Number, you would use setProperty() instead of setDirty. However, when the value of a property is an object that contains its own properties, use setDirty() to indicate when a value within the object has changed. In general, it is a good idea to call setProperty() rather than setDirty(), because setProperty() updates a property value only when that value has changed, whereas setDirty() forces synchronization on all subscribed clients.

Parameters
propertyName:String — The name of the property in the shared object.
 
value:Object (default = null) — The value of the property (an ActionScript object), or null to delete the property.

See also

Event detail
asyncErrorevent 
Event object type: flash.events.AsyncErrorEvent
AsyncErrorEvent.type property = flash.events.AsyncErrorEvent.ASYNC_ERROR

Dispatched when an exception is thrown asynchronously — that is, from native asynchronous code.

The AsyncErrorEvent.ASYNC_ERROR constant defines the value of the type property of an asyncError event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
targetThe object experiencing a network operation failure.
errorThe error that triggered the event.
netStatusevent  
Event object type: flash.events.NetStatusEvent
NetStatusEvent.type property = flash.events.NetStatusEvent.NET_STATUS

Dispatched when a SharedObject instance is reporting its status or error condition. The netStatus event contains an info property, which is an information object that contains specific information about the event, such as whether a connection attempt succeeded or whether the shared object was successfully written to the local disk.

Defines the value of the type property of a netStatus event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
infoAn object with properties that describe the object's status or error condition.
targetThe NetConnection or NetStream object reporting its status.

See also

syncevent  
Event object type: flash.events.SyncEvent
SyncEvent.type property = flash.events.SyncEvent.SYNC

Dispatched when a remote shared object (SharedObject) has been updated by the server.

Defines the value of the type property of a sync event object.

This event has the following properties:

PropertyValue
bubblesfalse
cancelablefalse; there is no default behavior to cancel.
currentTargetThe object that is actively processing the Event object with an event listener.
changeListAn array with properties that describe the array's status.
targetThe SharedObject instance that has been updated by the server.

See also

Examples

The following code creates (and on subsequent executions, retrieves) a shared object object using the ID "application-name". When the Save button is clicked, the saveValue() method attempts to save a property named savedValue to the data property of the SharedObject object. If Flash Player must ask for permission to save the data, when the user grants or denies permission the onFlushStatus() method is called. When the Clear button is clicked, the clearValue() method deletes the value saved in savedValue; the next time the SWF file is loaded, the value that is retrieved is undefined.
package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.events.NetStatusEvent;
    import flash.net.SharedObject;
    import flash.net.SharedObjectFlushStatus;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFieldType;
    
    public class SharedObjectExample extends Sprite {
        
        private var mySo:SharedObject;
        
        public function SharedObjectExample() {
            buildUI();
            saveBtn.addEventListener(MouseEvent.CLICK, saveValue);
            clearBtn.addEventListener(MouseEvent.CLICK, clearValue);
            
            mySo = SharedObject.getLocal("application-name");
            output.appendText("SharedObject loaded...\n");
            output.appendText("loaded value: " + mySo.data.savedValue + "\n\n");
        }

         private function saveValue(event:MouseEvent):void {
            output.appendText("saving value...\n");
            mySo.data.savedValue = input.text;
            
            var flushStatus:String = null;
            try {
                flushStatus = mySo.flush(10000);
            } catch (error:Error) {
                output.appendText("Error...Could not write SharedObject to disk\n");
            }
            if (flushStatus != null) {
                switch (flushStatus) {
                    case SharedObjectFlushStatus.PENDING:
                        output.appendText("Requesting permission to save object...\n");
                        mySo.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                        break;
                    case SharedObjectFlushStatus.FLUSHED:
                        output.appendText("Value flushed to disk.\n");
                        break;
                }
            }
            output.appendText("\n");
        }
        
        private function clearValue(event:MouseEvent):void {
            output.appendText("Cleared saved value...Reload SWF and the value should be \"undefined\".\n\n");
            delete mySo.data.savedValue;
        }
        
        private function onFlushStatus(event:NetStatusEvent):void {
            output.appendText("User closed permission dialog...\n");
            switch (event.info.code) {
                case "SharedObject.Flush.Success":
                    output.appendText("User granted permission -- value saved.\n");
                    break;
                case "SharedObject.Flush.Failed":
                    output.appendText("User denied permission -- value not saved.\n");
                    break;
            }
            output.appendText("\n");

            mySo.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
        }
        
        // UI elements
        private var inputLbl:TextField;
        private var input:TextField;
        private var output:TextField;
        private var saveBtn:Sprite;
        private var clearBtn:Sprite;
    
        private function buildUI():void {
            // input label
            inputLbl = new TextField();
            addChild(inputLbl);
            inputLbl.x = 10;
            inputLbl.y = 10;
            inputLbl.text = "Value to save:";
            
            // input TextField
            input = new TextField();
            addChild(input);
            input.x = 80;
            input.y = 10;
            input.width = 100;
            input.height = 20;
            input.border = true;
            input.background = true;
            input.type = TextFieldType.INPUT;
            
            // output TextField
            output = new TextField();
            addChild(output);
            output.x = 10;
            output.y = 35;
            output.width = 250;
            output.height = 250;
            output.multiline = true;
            output.wordWrap = true;
            output.border = true;
            output.background = true;
            
            // Save button
            saveBtn = new Sprite();
            addChild(saveBtn);
            saveBtn.x = 190;
            saveBtn.y = 10;
            saveBtn.useHandCursor = true;
            saveBtn.graphics.lineStyle(1);
            saveBtn.graphics.beginFill(0xcccccc);
            saveBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5);
            var saveLbl:TextField = new TextField();
            saveBtn.addChild(saveLbl);
            saveLbl.text = "Save";
            saveLbl.selectable = false;
            
            // Clear button
            clearBtn = new Sprite();
            addChild(clearBtn);
            clearBtn.x = 230;
            clearBtn.y = 10;
            clearBtn.useHandCursor = true;
            clearBtn.graphics.lineStyle(1);
            clearBtn.graphics.beginFill(0xcccccc);
            clearBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5);
            var clearLbl:TextField = new TextField();
            clearBtn.addChild(clearLbl);
            clearLbl.text = "Clear";
            clearLbl.selectable = false;
        }
    }
}




Take a survey


Comments


Rambo 007 said on Mar 28, 2008 at 8:04 AM :
Towards the top of the general description the text reads:

"Alternatively, if you set the shared object's properties to null before the calculator application is closed, the next time the application runs, it opens without any prior values."

I think it might be better to encourage the use of the clear() method which removes not only all the properties' values (whatever the properties are that have been set on the SharedObject), as well as freeing the disk space that's used to store the properties.


A second comment is that the documentation doesn't fully point out that SharedObjects use Flex serialization to store the objects, and that without doing special things, user declared classes will not serialize/deserialize properly, and will instead be returned as generic instances of type Object.

[If you include my immediately prior comment text about how to make ObjectUtils.copy() work with user-written classes and Flex native classes like Dictionary, you can reference that text here to describe how to achieve more "correct" round trip behavior for these kinds of classes]

 

RSS feed | Send me an e-mail when comments are added to this page | Comment Report

Current page: http://livedocs.adobe.com/flex/201/langref/flash/net/SharedObject.html