Recipe 17.2.
Writing Data to a Shared Object
Problem
You want
to add data to an LSO.
Solution
Add the values as properties of the shared
object's data object.
Discussion
Shared objects have a special built-in property
named data. The data property is an object to
which you should add any information that you want stored in the
shared object:
// Store a username value to the example shared object.
example.data.username = "Darron";
Unlike previous versions of ActionScript,
properties can no longer be attached directly to the shared object.
A compile-time error is generated when trying to store data on the
SharedObject instance itself instead of in the data
property. This prevents potential erroneous attempts to save
data:
example.variable = "This will cause a compile-time error.";
Additionally, trying to assign a value to the
data property directly is incorrect:
example.data = "This will cause another compile-time error.";
The correct approach is to attach the value to a
new property under the data property, as follows:
example.data.variable = "This is the correct way to store data.";
You can store several native ActionScript
datatypes to the shared object's data property, as
follows.
example.data.exampleArray = new Array( "a", "b", "c" );
example.data.exampleDate = new Date();
example.data.exampleObject = { key1: "example", key2: -12, key3: null };
However, you cannot store visual elements (such
as movie clips, sprites, buttons, or text fields) or shared objects
themselves to a shared object's data property so that the
data persists correctly between sessions.
|