How do i delete text line from a txt file? ActionScript - actionscript-3

Good morning! So here is basic code, which i get from the "Mobile Development with Adobe Flash Professional CS5.5 and Flash Builder 4.5" tutorial. Pretty much basic code, but those bastards didnt gave any information about DELETE function. THis is my first time application for this, so help is needed!
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
height="494" creationComplete="readFile()">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
[Bindable] public var todo_items:ArrayCollection;
private function readFile():void
{
var todoFile:File =File.applicationStorageDirectory.resolvePath("todo.txt");
if (todoFile.exists)
{
var fs:FileStream = new FileStream();
fs.open(todoFile, FileMode.READ);
var result:String = fs.readUTFBytes(fs.bytesAvailable);
var items:Array = result.split("\n");
items.pop();
todo_items = new ArrayCollection(items);
fs.close();
}
else { trace("Aplication cant find the file");
}
}
private function writeFile():void
{
var todoFile:File = File.applicationStorageDirectory.resolvePath("todo.txt");
var fs:FileStream = new FileStream();
fs.open(todoFile, FileMode.APPEND);
fs.writeUTFBytes(task_txt.text + "\n");
fs.close();
readFile();
}
private function deleteFile():void
{
//????????????? HEEEEELP !!!!!!!!!!
}
]]>
</fx:Script>
<s:List id="todo_list" left="10" right="10" top="146" bottom="87" dataProvider="{todo_items}"/>
<s:Button left="11" right="10" top="69" height="65" label="Save task" click="writeFile()"
enabled="{task_txt.text.length > 0}"/>
<s:TextInput id="task_txt" left="10" right="10" top="10" height="51" prompt="Specify a task"/>
<s:Button left="10" right="10" bottom="14" label="Delete"
click="todo_items.removeItemAt(todo_list.selectedIndex); deleteFile()"
enabled="{todo_list.selectedIndex != -1}"/>

What you want to do is
read in all of the data from the file, just like readFile is doing.
delete from that data whatever lines you want to delete.
write the data back to the file - like writeFile is doing - in FileMode.WRITE mode, as you want it to overwrite, not append.
If you can't quite figure this out and need code instead of a guide, feel free to comment on here and I'll give you more than just pointers.
The code in readFile (all of it) reads in the data from the file into an ArrayCollection called todo_items.
If you want to remove an item from the file, you want to remove it from that ArrayCollection (something like todo_items.removeItemAt(index)).
Now, you have an ArrayCollection containing the data you want to be in the file. At this point, you need to imitate what writeFile() is doing, but with FileMode.WRITE, and you want to write out every item in your list, instead of the one item in the textbox you want to add.
private function deleteFile():void
{
var todoFile:File = File.applicationStorageDirectory.resolvePath("todo.txt");
var fs:FileStream = new FileStream();
fs.open(todoFile, FileMode.WRITE);
for(var item:String in todo_items)
{
fs.writeUTFBytes(item + "\n")
}
fs.close();
readFile();
}
On a somewhat related note - I don't think 'deleteFile' is a good name for what you are doing here. You might want a deleteItem() method that deletes the selected item, and then a saveFile() method that contains the code above.

I presume the deleteFile method is intended to delete the file? If so, Adobe's Reference documents the File class and deletion this is normally a good place to start when exploring classes.
private function deleteFile():void
{
var todoFile:File = File.applicationStorageDirectory.resolvePath("todo.txt");
todoFile.deleteFile()
}

Related

Playing a video with flex, AS3

I am currently trying to make a game on flex and one of the problems I ran in to is how to play a short animation at the beginning. This is what I have so far:
Game.mxml
<?xml version="1.0"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
name="Game"
backgroundColor="#000000"
horizontalAlign="center"
creationComplete="Init();"
enterFrame="UpdateFrame();"
paddingLeft="0"
paddingTop="0"
paddingBottom="0"
paddingRight="0"
width="800" height="600">
<mx:Script>
<![CDATA[
include "Game.as";
]]>
</mx:Script>
<mx:Canvas id="gamePanel" x="0" y="0" width="100%" height="100%" mouseDown="MouseDown(event)" mouseUp="MouseUp(event)" mouseMove="MouseMoved(event)"/>
</mx:Application>
and Game.as
import flash.display.*;
import flash.events.*;
import flash.external.ExternalInterface;
import mx.events.*;
import mx.controls.*;
[Embed(source="MyVideoClip.flv")] private var MyVideoClip:Class;
public function Init():void
{
var MyVideo:Video = new Video(800, 600);
addChild(MyVideo);
var qNetConnection:NetConnection = new NetConnection();
qNetConnection.connect(null);
var qNetStream:NetStream = new NetStream(qNetConnection);
MyVideo.attachNetStream(qNetStream);
qNetStream.client = new Object();
qNetStream.play(MyVideoClip);
}
private function UpdateFrame():void
{
}
private function MouseDown(event:MouseEvent):void
{
}
private function MouseUp(event:MouseEvent):void
{
}
private function MouseMoved(event:MouseEvent):void
{
}
I am rather new to Flex and AS3 so most of this code was ripped off web tutorials. Whenever I try to compile it I get: 'Error: 'MyVideoClip.flv' does no have a recongnized extention, and a mimeType was not provided. Error: unable to transcode 'MyVideoClip.flv''
If I remove the 'embed' line and replace MyVideoClip with "MyVideoClip.flv" in the play() function, the code compiles with no errors, but when I open the SWF all I get is a black screen. What am I doing terribly wrong?
Thanks in advance!!
Try setting the mime-type, e.g.:
[Embed(source = "MyVideoClip.flv", mimeType = "application/octet-stream")]
You embedded the video file (its bytes) into the output SWF. So now NetStream must play from a bytes source. Just set a byteArray as equal to new MyVideoClip(); and append to NetStream.
Try this...
[Embed(source="MyVideoClip.flv", mimeType="application/octet-stream")] private var MyVideoClip:Class; //# embed the FLV's bytes
public var VideoClipBytes : ByteArray;
public var MyVideo:Video;
public var qNetConnection:NetConnection;
public var qNetStream:NetStream;
public function Init():void
{
VideoClipBytes = new MyVideoClip() as ByteArray; //# fill a byte Array with embedded bytes
qNetConnection = new NetConnection(); qNetConnection.connect(null);
qNetStream = new NetStream(qNetConnection);
qNetStream.client = new Object();
MyVideo = new Video(800, 600);
MyVideo.attachNetStream(qNetStream);
addChild(MyVideo);
qNetStream.play(null); //# play mode is now bytes
qNetStream.appendBytesAction(NetStreamAppendBytesAction.RESET_BEGIN); //# ready for new audio/video data
qNetStream.appendBytes( VideoClipBytes ); //# add bytes to decoder queue (playback)
}
PS : I made some of your variables as public so later you can access & control them from any other functions. Remember if you make var inside a public function it stays valid only in that one function and doesn't exist to other functions. Best make such vars as publicly available to all functions.

Displaying a progress dialog before calling URLLoader.load in flex?

I'm developing a flex application (run in web browser), that lets the user load a number of files and then sends them all to a server in one single multipart/form-data request.
My problem is this:
For security reasons, flash requires that the user initiates the URLLoader.load action by clicking on a button. That's ok, the user clicks the save button in the application and off we go.
Unfortunately, the uploading part of the request doesn't seem to be asynchronous, but only the downloading part. The data can be any size since the user can add an arbitrary number of files, so the upload can take a while to complete.
In an ideal world I would do something like this in the click handler of the save button:
PopupManager.createPopup(this, ProgressDialog, true);
doUpload();
Unfortunately this will result in the progressdialog being shown after the upload finishes.
So, can I defer the upload start until the popup has been shown, like this?
PopupManager.createPopup(this, ProgressDialog, true);
setTimeout(doUpload, 100);
Turns out I can't do this either, because of the security reasons mentioned above. This will throw a SecurityError: Error #2176.
Basically the problem is
A popup won't be visible until the code in the current frame has completed
URLLoader.load blocks until the upload part of the request is completed
The popup arrives too late, since the time consuming part is already over.
I can't wait for the popup, since the load action has to be initiated by the user click.
Is there any way whatsoever to work around this limitation?
Here is a small application that illustrates the problem. Button two and three will throw the SecurityError.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="419" height="250">
<fx:Script>
<![CDATA[
import mx.core.IFlexDisplayObject;
import mx.managers.PopUpManager;
private var urlLoader:URLLoader;
private var popup:IFlexDisplayObject;
protected function sendNowButton_clickHandler(event:MouseEvent):void {
trace(">> URLLoaderSendTest.sendNowButton_clickHandler(event)");
popup = PopUpManager.createPopUp(this, ProgressDialog, true);
doLoad();
trace("<< URLLoaderSendTest.sendNowButton_clickHandler(event)");
}
protected function sendWithSetTimeoutButton_clickHandler(event:MouseEvent):void {
trace(">> URLLoaderSendTest.sendLaterButton_clickHandler(event)");
popup = PopUpManager.createPopUp(this, ProgressDialog, true);
setTimeout(doLoad, 200);
trace("<< URLLoaderSendTest.sendLaterButton_clickHandler(event)");
}
protected function sendWithCallLaterButton_clickHandler(event:MouseEvent):void {
trace(">> URLLoaderSendTest.sendWithCallLaterButton_clickHandler(event)");
popup = PopUpManager.createPopUp(this, ProgressDialog, true);
callLater(doLoad);
trace("<< URLLoaderSendTest.sendWithCallLaterButton_clickHandler(event)");
}
private function doLoad():void {
trace(">> URLLoaderSendTest.doLoad()");
var bytes:ByteArray = new ByteArray();
bytes.writeInt(1);
var request:URLRequest = new URLRequest("http://localhost/test/");
request.method = URLRequestMethod.POST;
request.contentType = "multipart/form-data";
request.data = bytes;
urlLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, loaderComplete);
urlLoader.load(request);
trace("<< URLLoaderSendTest.doLoad()");
}
protected function loaderComplete(event:Event):void {
trace(">> URLLoaderSendTest.loaderComplete(event)");
PopUpManager.removePopUp(popup);
}
]]>
</fx:Script>
<s:Button id="sendNowButton" x="10" y="10"
label="Send now"
click="sendNowButton_clickHandler(event)"/>
<s:Button id="sendWithsetTimeoutButton" x="10" y="40"
label="Send with setTimeout"
click="sendWithSetTimeoutButton_clickHandler(event)"/>
<s:Button id="sendWithCallLaterButton" x="10" y="70"
label="Send with callLater"
click="sendWithCallLaterButton_clickHandler(event)"/>
</s:Application>

How to convert a string to an object

I'm trying to use a sharedObject to coordinate the movement of several objects on the stage between multiple game players. I think that I'm very close but I seem to be having a problem converting a string stored in the sharedObject into an instance of the Ball class.
My problem is in the soSync function.
I think I need to convert into an object the value of 'objectMoved' that is stored in the sharedObject. I can trace the name of the selected object, but I cannot retrieve it as an object.
How do I store the selected object in a sharedObject and then use it to coordinate motion with the other game players?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
public var nc:NetConnection;
private var connectionURL:String = "rtmp://server address...";
public var remoteSO:SharedObject;
private var checker:Ball;
public function init():void{
//Create new checkers; place them and create listeners
for (var i:int = 0; i < 3; i++){
checker = new Ball;
checker.x = 150 + (i * 110);
checker.y = 150;
checker.name = String(i);
this.addChild(checker);
checker.addEventListener(MouseEvent.MOUSE_DOWN,handleMouseDown);
}
// Establish connection to the server
nc = new NetConnection();
//Listener triggered by the NetConnection connection
nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
nc.connect(connectionURL);
}
private function netStatusHandler(e:NetStatusEvent):void {
if(e.info.code == "NetConnection.Connect.Success"){
createRemoteSO();
}
}
private function handleMouseDown(e:MouseEvent):void{
//Show which object has been selected
objectInfo.text = "Clicked: "+String(e.currentTarget);
e.currentTarget.startDrag();
e.currentTarget.addEventListener(MouseEvent.MOUSE_MOVE,dragging);
e.currentTarget.addEventListener(MouseEvent.MOUSE_UP,handleMouseUp)
//Update the remote shared object from this client
function dragging(e:MouseEvent):void{
objectInfo.text = "Dragging: "+String(e.currentTarget);
//Set the shared object
remoteSO.setProperty("objectMoved",e.currentTarget.name);
remoteSO.setProperty("x",e.currentTarget.x);
remoteSO.setProperty("y",e.currentTarget.y);
}
function handleMouseUp(e:MouseEvent):void{
e.currentTarget.stopDrag();
objectInfo.text = ""
e.currentTarget.removeEventListener(MouseEvent.MOUSE_MOVE,dragging)
}
}
private function createRemoteSO():void{
// Create reference to the remote shared object
remoteSO = SharedObject.getRemote("remoteSO",nc.uri,false);
remoteSO.connect(nc);
//Listener to handle changes to the remote shared object
remoteSO.addEventListener(SyncEvent.SYNC, soSync);
}
//Called when a change is made to the remote shared object by other clients
private var counter:int;
private function soSync(se:SyncEvent):void {
if(remoteSO.data.objectMoved){
this.getChildByName(remoteSO.data.objectMoved).x = remoteSO.data.x;
this.getChildByName(remoteSO.data.objectMoved).y = remoteSO.data.y;
}else{
trace("Object does not exist")
}
}
]]>
</mx:Script>
<mx:Text x="147" y="51" text="Selected object"/>
<mx:TextArea id="objectInfo" x="237" y="50"/>
</mx:Application>
Ball.mxml
<?xml version="1.0" encoding="utf-8"?>
<mx:UIComponent xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()">
<mx:Script>
<![CDATA[
import mx.events.FlexEvent;
private function init():void{
var child:Shape = new Shape();
child.graphics.beginFill(0xff0000, .5);
child.graphics.drawCircle(0, 0, 50);
child.graphics.endFill();
this.addChild(child);
}
]]>
</mx:Script>
</mx:UIComponent>
I think you could use getChildByName("String/ObjectName here").
So in your case...
this.getChildByName(remoteSO.data.objectMoved).y = remoteSO.data.y;
Alternatively, could you not just add the physical object itself when using setProperty as opposed to the objects name. Like so...
remoteSO.setProperty("objectMoved",e.currentTarget);
Your Ball object seems to be a DisplayObject, which are unable to be saved in a shared object as a whole. You can, however, instantiate a Ball object, read properties out of the SO and assign them to your ball. The properties in question seem to be x and y, and not objectMoved, as your ball's name will most likely be in line of instance389 which does not spell a thing if you lose the naming context, and even if not, you can only find a child by name if it still exists. So, if you have only one object of type Ball, you assign it the X and Y read from the SO, if not, you should store several balls in your SO, so you will instantiate them later and preserve all of their coordinates.

Flex: Why are TileList images disappearing on drag?

I'm developing a Flex Air (desktop) application that loads images from the local filesystem into a TileList. The user will then be able to drag (copy) these images out of the list onto another control.
I've finally got the images showing up correctly (and not disappearing after scrolling the TileList) but they seem to disappear from the TileList at the start of a drag operation.
I come from a .NET background and am just learning AS3/Flex, so if you see me using any anti-patterns here, feel free to point them out!
Sample code follows (I've tried to make this as minimal as possible).
Test.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
[Bindable]
protected var _pics:ArrayCollection = new ArrayCollection();
protected function picsList_creationCompleteHandler(event:FlexEvent):void
{
const imageFolderPath:String = "c:\\users\\bbrooks\\Pictures";
var imageDir:File = new File(imageFolderPath);
var imageFiles:Array = imageDir.getDirectoryListing();
for each(var imageFile:File in imageFiles)
{
_pics.addItem(new PictureObject(imageFile.nativePath));
}
// give images a chance to load
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, onTimerExpired);
timer.start();
}
protected function onTimerExpired(event:TimerEvent):void
{
picsList.dataProvider = _pics;
}
]]>
</fx:Script>
<mx:TileList id="picsList" x="0" y="0" width="100%" height="100%" dragEnabled="true" dragMoveEnabled="false"
creationComplete="picsList_creationCompleteHandler(event)" >
<mx:itemRenderer>
<fx:Component>
<mx:Image width="75" height="75" source="{data.image}" />
</fx:Component>
</mx:itemRenderer>
</mx:TileList>
</s:WindowedApplication>
PictureObject.as:
package
{
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import mx.controls.Image;
[Bindable]
[RemoteClass]
public class PictureObject extends Object
{
protected var _image:Image = null;
public function get image():Image { return _image; }
public function set image(newValue:Image):void { _image = newValue; }
public function PictureObject(path:String)
{
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
imageLoader.load(new URLRequest(path));
}
protected function onImageLoaded(e:Event):void
{
var imageLoader:Loader = LoaderInfo(e.target).loader;
var bmp:Bitmap = Bitmap(imageLoader.content);
_image = new Image();
_image.smoothBitmapContent = true;
_image.source = new Bitmap(bmp.bitmapData);
_image.width = imageLoader.width;
_image.height = imageLoader.height;
}
}
}
I will mostly reply to your secondary question (guessing it will resolve the primary in one fell swoop): as anti-patterns go, this is not a bad example ;)
You are manually loading the images while the Image class has the loading built-in; just give a URL to its source property and it will automatically load it.
You are setting an Image instance as the source of another Image instance; the source property expects URLs or ByteArrays; I'm surprised it doesn't throw an error; the Image class is probably smart enough to extract the source of the other Image instance.
The Timer is redundant. As said, an Image automatically takes care of loading its content.
The s:Image tag isn't wrapped in an ItemRenderer and hence should have no access to a data property: this code shouldn't even compile.
There's no point in having a Bindable property _pics if you don't plan on binding it.
You use the mx TileList. Why not use the more "modern" Spark version? (This doesn't mean the mx class won't work in a Spark application though).
So you have a lot of deleting to do. You can scrap the PictureObject class altogether; remove the Timer code; and just add the URL Strings to the _pics collection. As a plus you could also replace the mx TileList with a Spark List with TileLayout; something like this:
<s:List id="picsList">
<s:layout>
<s:TileLayout />
</s:layout>
<s:itemRenderer>
<fx:Component>
<s:ItemRenderer>
<s:Image source="{data}" />
</s:ItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:List>
The ActionScript part could be reduced to this:
const imageFolderPath:String = "c:\\users\\bbrooks\\Pictures";
var imageDir:File = new File(imageFolderPath);
var imageFiles:Array = imageDir.getDirectoryListing();
picsList.dataProvider = new ArrayCollection(imageFiles);
Thanks RIAstar. Your answer put me on the track to solving the problem. The new sample code appears below.
The original problem seems to have been with the mx:Image control. Not sure why, but using the s:Image control seems to work.
Granted, this could be accomplished without the PictureObject class at all by simply setting the data source to a list of file paths, but I'm using the image data later and I wanted to get it working by supplying the image data to the custom renderer dynamically.
Test.mxml:
<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
import spark.components.Image;
protected var _pics:ArrayCollection = new ArrayCollection();
protected function picsList_creationCompleteHandler(event:FlexEvent):void
{
const imageFolderPath:String = "c:\\users\\bbbrooks\\Pictures";
var imageDir:File = new File(imageFolderPath);
var imageFiles:Array = imageDir.getDirectoryListing();
for each(var imageFile:File in imageFiles)
{
if (imageFile.extension == "jpg")
{
_pics.addItem(new PictureObject(imageFile.nativePath));
}
}
// give images a chance to load
var timer:Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, onTimerExpired);
timer.start();
}
protected function onTimerExpired(event:TimerEvent):void
{
picsList.dataProvider = _pics;
}
]]>
</fx:Script>
<s:List id="picsList" x="0" y="0" width="100%" height="100%"
creationComplete="picsList_creationCompleteHandler(event)"
dragEnabled="true" dragMoveEnabled="false">
<s:layout>
<s:TileLayout />
</s:layout>
<s:itemRenderer>
<fx:Component>
<s:ItemRenderer>
<s:Image id="imageDisplay"
width="75" height="75" source="{data.bmp}" />
</s:ItemRenderer>
</fx:Component>
</s:itemRenderer>
</s:List>
</s:WindowedApplication>
PictureObject.as
package
{
import flash.display.Bitmap;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.events.Event;
import flash.net.URLRequest;
import mx.controls.Image;
[RemoteClass]
[Bindable]
public class PictureObject extends Object
{
protected var _bmp:Bitmap = null;
public function get bmp():Bitmap { return _bmp; }
public function set bmp(newValue:Bitmap):void { _bmp = newValue; }
public function PictureObject(path:String)
{
var imageLoader:Loader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
imageLoader.load(new URLRequest(path));
}
protected function onImageLoaded(e:Event):void
{
var imageLoader:Loader = LoaderInfo(e.target).loader;
// create our own copy of the bits in the Loader
var bmp:Bitmap = Bitmap(imageLoader.content);
_bmp = new Bitmap( Bitmap(imageLoader.content).bitmapData );
}
}
}

EFFECT_REPEAT not firing on every iteration of Animate instance when losing focus

I'm not sure if that title is descriptive enough, but here is the basic issue. I have a spark.effects.Animate instance repeating n times with a listener on the EFFECT_REPEAT event. In that event's listener, I'm incrementing a variable. Logic would dictate that if the variable started at 0 and the animation was played with a repeatCount of 3, the variable would be 2 when finished. This works fine, until I focus a different tab. When doing this, on occasion, the repeat event isn't fired/handled (or the animation is just not actually doing the animation) and my count isn't correct when finished.
This is a fully functioning example built against Flex 4.5. To duplicate just click the GO button and maintain focus on the TAB. Then click it again and switch tabs and switch back. The counts don't match.
How can I fix this so that the repeat event is called consistently?
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" width="600" height="400" applicationComplete="application1_applicationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.controls.Image;
import mx.events.EffectEvent;
import mx.events.FlexEvent;
import spark.effects.Animate;
import spark.effects.animation.MotionPath;
import spark.effects.animation.SimpleMotionPath;
private var animate:Animate;
private var someCounter:int = 0;
protected function application1_applicationCompleteHandler(event:FlexEvent):void
{
// Create the graphic
var img:Image = new Image();
img.source = "http://www.google.com/intl/en_com/images/srpr/logo3w.png";
// Add the graphic
addElement( img );
// Create the motion path
var smp:SimpleMotionPath = new SimpleMotionPath();
smp.property = "x";
smp.valueFrom = 0;
smp.valueTo = this.width - 275;
// Add the motion path to a Vector
var paths:Vector.<MotionPath> = new Vector.<MotionPath>();
paths.push( smp );
// Create the animation
animate = new Animate();
animate.easer = null;
animate.target = img;
animate.duration = 150;
animate.repeatCount = 15;
animate.motionPaths = paths;
animate.addEventListener( EffectEvent.EFFECT_REPEAT, animate_effectRepeatHandler );
animate.addEventListener( EffectEvent.EFFECT_END, animate_effectEndHandler );
}
private function animate_effectRepeatHandler( event:EffectEvent ):void
{
lblCounter.text = someCounter.toString();
someCounter++;
}
private function animate_effectEndHandler( event:EffectEvent ):void
{
lblCounter.text = someCounter.toString(); // Sometimes doesn't equal animate.repeatCount - 1
}
protected function button1_clickHandler(event:MouseEvent):void
{
if( !animate.isPlaying )
{
someCounter = 0;
animate.play();
}
}
]]>
</fx:Script>
<mx:Label id="lblCounter" horizontalCenter="0" bottom="50" width="150" height="50" textAlign="center" />
<mx:Button horizontalCenter="0" bottom="0" label="GO" width="150" height="50" click="button1_clickHandler(event)" />
</s:Application>