Flash CS3 - Flash CS4

Free tutorials and scripts for all.
Actionscript 3.0

SharedObject with Actionscript 3.0

This is a discussion on SharedObject with Actionscript 3.0 within the Tutorials forums, part of the English Forums category; If you are trying to understand how the SharedObject works with Flash CS3, follow this tutorial and you will soon ...


Go Back   Forum Flash CS3 Flash CS4 > English Forums > Tutorials

Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
  4 links from elsewhere to this Post. Click to view. #1 (permalink)  
Old 23-09-07, 13:32
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,446
Rep Power: 6
Flep is on a distinguished road
SharedObject with Actionscript 3.0

If you are trying to understand how the SharedObject works with Flash CS3, follow this tutorial and you will soon know a lot more about this topic.

The ShareObject class is used to read or "store" data on the user"s computer.* To understand better, an easy comparison for the SharedObject would be the browser"s cookies.

This class is very useful and used a lot in game"s development.
I will make an example.
Let us say that we developed a game with Flash CS3.* The user will need to insert its own details so to be able to store his score and his name.* If the user would want to play more games, he would often be annoyed by the fact of having to enter his details once again at each game.
Instead, using the SharedObject class, our user could play as many games as he wants, entering once his personal details which would be memorized in a file by Flash and kept in the user"s computer.

The following example will ask you to insert your name, city and age.* Once "SALVA" clicked, Flash will save those data on your computer.* If you do a refresh at that point, you will see that Flash has retrieved your details successfully.
You can also delete your details and this time, after a page refresh, you will be asked to enter your details once again.





I create a FLA and save it as "main.fla".
Into which:
Frame 1:
- a MovieClip with an instance name "form_mc" which will contain 3 dynamic text fields "nome_txt", "citta_txt" and "eta_txt". Those three text fields need to be then declared as input so that the user can overwrite them. It will also contain a button with an instance name "save_btn".
- a MovieClip with an instance name "info_mc" which will contain a dynamic text field named "info_txt" and a button named "delete_btn".
- a dynamic text field named "output_txt"*.

Frame 2:
- a static text field which will advise that the data have been saved correctly.
.
*I create a Document Class, as AS file saved as "Main.as", implemented the following way:
Code:
package
{
	import flash.display.MovieClip;
	import flash.text.TextField;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.net.SharedObject;
	import flash.net.SharedObjectFlushStatus;

	public class Main extends MovieClip
	{
		private var _so:SharedObject;
		
		public function Main()
		{
			stop();
			
			init();
			checkSharedObject();
		}
		
		private function init():void
		{
			form_mc.visible=false;
			form_mc.x=stage.stageWidth/2;
			form_mc.y=stage.stageHeight/2;
			
			info_mc.visible=false;
			info_mc.x=form_mc.x;
			info_mc.y=form_mc.y;
			
			form_mc.save_btn.label='SALVA';
			info_mc.delete_btn.label='CANCELLA I TUOI DATI';
		}
		
		private function checkSharedObject():void
		{
			_so=SharedObject.getLocal('FlepStudio');
			
			if(_so.data.nome==undefined||_so.data.citta==undefined||_so.data.eta==undefined)
				displayAll();
			else
				displayInfo();
		}
		
		private function displayAll():void
		{
			form_mc.visible=true;
			form_mc.save_btn.addEventListener(MouseEvent.CLICK, saveCookie);
            
		}
		
		private function displayInfo():void
		{
			info_mc.visible=true;
			info_mc.delete_btn.addEventListener(MouseEvent.CLICK, clearCookie);
			info_mc.info_txt.text='Tu sei '+_so.data.nome+'\n'+
												'abiti a '+_so.data.citta+'\n'+
												'ed hai '+_so.data.eta+' anni';
		}
		
		private function saveCookie(evt:MouseEvent):void
		{
			var flushStatus:String=null;
			
			_so.data.nome=evt.currentTarget.parent.nome_txt.text;
			_so.data.citta=evt.currentTarget.parent.citta_txt.text;
			_so.data.eta=evt.currentTarget.parent.eta_txt.text;
			try 
			{
				flushStatus=_so.flush(10000);
			} 
			catch (error:Error) 
			{
				trace('Errore...non riesco a scrivere i dati su disco');
			}
			if(flushStatus != null) 
			{
				switch(flushStatus)
				{
					case SharedObjectFlushStatus.PENDING:
					output_txt.appendText('Richiesta permessi per salvataggio oggetto in corso...\n');
					_so.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
					break;
						
					case SharedObjectFlushStatus.FLUSHED:
					gotoAndStop(2);
					break;
				}
			}
		}
		
		private function onFlushStatus(event:NetStatusEvent):void
		{
			output_txt.appendText("L'utente ha chiuso la finestra di dialogo.\n");
			switch (event.info.code) 
			{
				case "SharedObject.Flush.Success":
				output_txt.appendText("L' utente ha confermato il permesso.\n");
				break;
				
				case "SharedObject.Flush.Failed":
				output_txt.appendText("L' utente ha negato il permesso.\n");
				break;
			}
			output_txt.appendText("\n");
			
			_so.removeEventListener(NetStatusEvent.NET_STATUS,onFlushStatus);
		}
		
		private function clearCookie(mevt:MouseEvent):void
		{
			info_mc.info_txt.text='I tuoi dati sono stati cancellati dallo Shared Object, chiudi e riapri il browser e vedrai...';
			delete _so.data.nome;
			delete _so.data.citta;
			delete _so.data.eta;
		}
	}
}
Let us analyse the code

Properties

An instance of the SharedObject class
private var _so:SharedObject;

Constructor function
I stop the time line at the first frame
stop();
I call the method "init"
init();
I call the method "checkSharedObject"
checkSharedObject();

Methods
init();
I impost "form_mc" to invisible and position it to the stage centre
form_mc.visible=false;
form_mc.x=stage.stageWidth/2;
form_mc.y=stage.stageHeight/2;
I impost "info_mc" to invisible and position it to the stage centre
info_mc.visible=false;
info_mc.x=form_mc.x;
info_mc.y=form_mc.y;
I assign a text to the button"s labels
form_mc.save_btn.label='SAVE';
info_mc.delete_btn.label='DELETE YOUR DATA';

checkSharedObject();
I check if an object named "FlepStudio" written by Flash already exists on the user"s computer, using the method "getLocal"
_so=SharedObject.getLocal(FlepStudio);
if it does exist, I check that the 3 properties "nome", "citte" and "eta" are present. If one or all of them are undefined, I call the method "displayAll"
if(_so.data.nome==undefined||_so.data.citta==undef ined||_so.data.eta==undefined)
displayAll();
otherwise if the three properties are defined, I call the method "displayInfo"
else
displayInfo();

displayAll();
"form_mc" is visibile as no object has been found
form_mc.visible=true;
I add a listener to the CLICK of "save_btn" placed into "form_mc". The event will call the method "saveCookie"
form_mc.save_btn.addEventListener(MouseEvent.CLICK , saveCookie);

displayInfo();
"info_mc" is visibile as an object has been found
info_mc.visible=true;
I add a listener to the CLICK of "delete_btn" placed into "form_mc". The event will call the method "clearCookie"
info_mc.delete_btn.addEventListener(MouseEvent.CLI CK, clearCookie);
I display the information retrieved from the object found on the user"s computer
info_mc.info_txt.text='You are'+_so.data.nome+'\n'+'you live in'+_so.data.citta+'\n'+'and you are'+_so.data.eta+' years old';

saveCookie();
a create a String variable and I impost its value to null to check if the operation will success
var flushStatus:String=null;
I assign three properties to the data object "_so" (instance of SharedObject) which at their turns will assign the written text to the text fields
_so.data.nome=evt.currentTarget.parent.nome_txt.te xt;
_so.data.citta=evt.currentTarget.parent.citta_txt. text;
_so.data.eta=evt.currentTarget.parent.eta_txt.text ;
I should now check once again that all the fields have been completed.
I let you deal with that part and start the process of writing
try
{
I assign to flushStatus a value returned by the method "flush" of the SharedObject class
flushStatus=_so.flush(10000);
}
catch (error:Error)
{
If the process is not successful, I trace an error message. This message could also be displayed to the user if wanted.
trace("Error...can't write data on disk");
}
if(flushStatus != null)
{
If the process of writing has been successful, I check the value of "flushStatus"
switch(flushStatus)
{
If the value of "flushStatus" is pending (returned by the event PENDING of the SharedObjectFlushStatus class), it certainly means that the user has a security system which requires confirm before accepting the cookie. So the user should be advised that he needs to accept the cookie to proceed. At this point, I must check if the user accept it or not. To do it, I add a listener to "_so" for the event NET_STATUS of the NetStatusEvent which will then call the method "onFlashStatus"
case SharedObjectFlushStatus.PENDING:
output_txt.appendText('Requesting permissions...\n');
_so.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
break;
If the value of "flushStatus" is "flushed", I move the play head to frame 2 of the main time line which will tell the user that the process has been successful
case SharedObjectFlushStatus.FLUSHED:
gotoAndStop(2);
break;
}
}

onFlashStatus()
at this time, the user will have accept or not the authorisation
output_txt.appendText("User closed the dialog.\n");
next, I will check, based on the value of the property "code" of the object "info" (itself from the event PENDING from the SharedObjectFlushStatus class). If accepted, I advise the user via the "output_txt"
switch (event.info.code)
{
case "SharedObject.Flush.Success":
output_txt.appendText("User confirmed permission.\n");
break;
if it has not been confirmed, I advise anyway the user that the authorization has not been given
case "SharedObject.Flush.Failed":
output_txt.appendText("User denied permissions.\n");
break;
}
I remove the listener NetStatusEvent.NET_STATUS
_so.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);

clearCookie();
this method is called if the user decide to delete his details, Once again I advise him with a message
info_mc.info_txt.text='Data has been deleted form Shared Object, refresh your browser and you'll see...';
I remove the three properties created first to the Sharedobject "_so"
delete _so.data.nome;
delete _so.data.citta;
delete _so.data.eta;

Source files:
Attached Files
File Type: zip SharedObject.zip (575.6 KB, 55 views)

__________________

 


I recommend: Essential Actionscript 3.0

- Non rispondo ai messaggi privati con domande tecniche. Apri una discussione sul forum !
- I do not reply technicians pvt messages. Open a thread !

Last edited by Flep; 28-08-08 at 06:33..
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #2 (permalink)  
Old 10-12-07, 03:09
Junior Member
 
Join Date: Sep 2007
Posts: 24
Rep Power: 0
lfdesign is on a distinguished road
Re: SharedObject with Actionscript 3.0

Hi,

Do you know if it's possible to build a flash menu (that remembers the pressed button) to use in a HTML site using this method?

I'm trying to do it but I'm having a lot of troubles...
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #3 (permalink)  
Old 10-12-07, 07:39
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,446
Rep Power: 6
Flep is on a distinguished road
Re: SharedObject with Actionscript 3.0

Hi,
i don't see the use of a shared object for a menu.
I think you could use a variable into Flash that contains the id of the pressed button.

... perhaps if you explane more we can get you
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #4 (permalink)  
Old 10-12-07, 13:22
Junior Member
 
Join Date: Sep 2007
Posts: 24
Rep Power: 0
lfdesign is on a distinguished road
Re: SharedObject with Actionscript 3.0

The idea of using the shared object is for retaining the id of the pressed button when the browser loads a new page...

For example... We are on page "index.html", and when we press the contacts button on the menu it loads "contacts.html"... I need the flash menu to retain the down state of that button...

For that I need to store an external variable somewhere and the only thing I've thought about is using shared object...

Do you have any other solution?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #5 (permalink)  
Old 10-12-07, 14:27
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,446
Rep Power: 6
Flep is on a distinguished road
Re: SharedObject with Actionscript 3.0

ok, i think you are right, SharedObjects can work fine for that
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Flash Multi Gallery
  #6 (permalink)  
Old 10-12-07, 14:39
Junior Member
 
Join Date: Sep 2007
Posts: 24
Rep Power: 0
lfdesign is on a distinguished road
Re: SharedObject with Actionscript 3.0

The problem is that I have some glitches...

For example... When the user leaves the site it should delete the shared object... Or else when the user comes back, the menu will be on the down state of the last link he visited...

I think this is not the best solution to have a Flash menu on a HTML site... Do you know any other?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #7 (permalink)  
Old 10-12-07, 14:48
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,446
Rep Power: 6
Flep is on a distinguished road
Re: SharedObject with Actionscript 3.0

Javascript + Actionscript ?
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #8 (permalink)  
Old 10-12-07, 15:12
Junior Member
 
Join Date: Sep 2007
Posts: 24
Rep Power: 0
lfdesign is on a distinguished road
Re: SharedObject with Actionscript 3.0

The problem is that I don't know nothing about Javascript...

Can you please take a look at my files?

http://www.lpfmultimedia.com/flep/Web.zip
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #9 (permalink)  
Old 10-12-07, 17:44
Administrator
 
Join Date: Jul 2007
Location: Cesena
Posts: 4,446
Rep Power: 6
Flep is on a distinguished road
Re: SharedObject with Actionscript 3.0

Me neither...
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

  #10 (permalink)  
Old 16-06-08, 04:43
Junior Member
 
Join Date: Jun 2008
Posts: 1
Rep Power: 0
n8Mills is on a distinguished road
Re: SharedObject with Actionscript 3.0

Hi, it might be a bit late now (7 months later), but why not invoke a function with the button press? This way you can load the .html and retain your variable until the function is completed.

Also, Flep, I wanted to comment on the above tutorial because it helped me a lot but there was one thing that took me two days to discover: When creating your own .fla you must input the name of the .as file in the Document class of the Properties in the .fla.

You made mention to this, but it was not obvious enough and this is an important step. Without that, the .fla will not know to look for an external .as file.

So, that's it! Thanks for your knowledge!

n8
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote

Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is On
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

Similar Threads

Thread Thread Starter Forum Replies Last Post
SharedObject con Actionscript 3.0 Flep Articoli e tutorials 2 17-09-08 15:24
AS3 e gli SharedObject Remoti, AIUTO! lorenz82 Actionscript 3.0 avanzato 2 12-01-08 19:04


All times are GMT. The time now is 20:34.


Powered by vBulletin versione 3.7.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0 RC4
Forum SiteMap


FlepStudio
by Filippo Lughi
P.IVA 03605860406