Event Dispatched From Setinterval
Hello, I'm a newbie and trying to get a handle on some actionscript. Been at it for a few days a few different ways and just can't get it all to work right.
My latest code is using someone's easing function that was posted here to draw lines slowly. However, I need to listen for when it's done before I start the next animation. Apparently you can't call another function from a function that was called with setinterval? How can I do thi? See code below. My fla calls a function in myClass called mainDoSomething. mainDoSomething calls the doSomething function via a setInterval. Now I can't seem to call the event dispatcher from the doSomething function. Is there any way I can do this?
Code: .as file:
import mx.events.EventDispatcher
class myClass{ public static var eline_mc:MovieClip; public static var delay:Number;
function dispatchEvent() {}; function addEventListener() {}; function removeEventListener() {};
functionmyClass{ mx.events.EventDispatcher.initialize(this); }
function sendMessage(p_msgtxt:String) { var eventObj:Object={target:this,type:"done"} eventObj.msgtxt = p_msgtxt; dispatchEvent(eventObj); }
function doSomething() {
trace(" Doing Something " );
if (time > easeTime) { sendMessage("All Done"); /// Does not work because inside setinterval? clearInterval (myClass.intv);
} updateAfterEvent (); }
function mainDoSomething(line_mc:MovieClip, delay:Number ) {
myClass.eline_mc = line_mc;
myClass.eline_mc = delay; myClass.intv = setInterval (doSomething, myClass.delay);
} /* End */
}
.fla file:
var SSpeed:Number = 7;
var myObject:myClass = new myClass();
myListnerObj = {};
//var myListnerObj:Object = new Object; myListnerObj.done = function(evtObj) { trace("all done: "); }
myObject.addEventListener("done",myListnerObj.done);
// draw the rect and trigger the event: this.createEmptyMovieClip("my_mc", this.getNextHighestDepth());
myObject.mainDoSomething(my_mc, SSpeed);
stop();
ActionScript.org Forums > ActionScript Forums Group > ActionScript 2.0
Posted on: 09-09-2006, 03:35 AM
View Complete Forum Thread with Replies
See Related Forum Messages: Follow the Links Below to View Complete Thread
Listener For Dispatched Event
Hi,
I had a problem which the majority of got sorted out with help from other people but it's left me with one last part i dont get...
I have a main.swf which loads into a loader an external swf called menu1.swf. I'm trying to get a function triggered in the main.swf when it recieves an event dispatched from the menu1.swf. The main problem i had was getting the event to dispatch from the loaded swf but that's now sorted. My main problem now is where to add the listener in the main.swf to listen out for this event.
I've been informed it's not the loader i should be attaching the listener to, but rather it's contents ( the function i want to call is to unload the loader once the event from the contents of that loader has been dispatched). Now the contents is menu1.swf, but i didnt think you could attach a listener to a swf? I was also told that once the loader has completed loading, the swf is no longer a swf, but instead becomes content.data...
So what am i attaching a listener to? should it be loader.content.data.addEventlistener(... );
it's got me stumped?
Finding From Which Instace An Event Is Dispatched From
Heyo AS.Org
I am wondering if there is a way to find out from which instance of a class an event has been called from.
Example:
PHP Code:
public function InitGame():void//creates two instances of the Planets() class { var eth = new Planets(); eth.addEventListener (MouseEvent.CLICK, PlanetClicked) addChild(eth) eth.x = 100 eth.y = 200 var mar = new Planets(); mar.addEventListener (MouseEvent.CLICK, PlanetClicked) addChild(mar) mar.x = 400 mar.y = 100 } public function PlanetClicked(event:Event) { trace ("what can I trace to find if this function was called from eth or mar?") }
thanks!
How To Embed A String Into A Dispatched Event?
Dear community,
I use events and listeners to forward user clicks on datagrid cells.
I would like to embed a string into a dispatched event to tell to my main class which file has to be downloaded.
Does anybody know how to embed a string into an event?
Thank you,
Chris
Should An Object Be Able To Hear A Dispatched Event From A Cousin?
You know what i mean?
Like if you have a farm object and there is a chicken on the farm but also a pig on the farm, and the pig is in the barn, and the chicken is in the coup, If the chicken dispatches an egg, and the pig is listening for it, will the pig hear it?
Im tired and thats the best way i can describe it right now because ive been up all night but my pig is not hearing my chickens egg.
URLLoader Complete Event Not Dispatched While Streaming Mp3
Hi all,
i'm trying to load binary data using the URLLoader object while a
sound object is streaming an mp3.
However, the COMPLETE event is only dispatched as soon as i stop
the audio stream.
here's the code snippets where i create the objects:
Class A
Code:
this.sound = new Sound(new URLRequest(someUrl), this.context);
Class B
Code:
var myData : URLRequest = new URLRequest(anotherUrl);
this.loader.load(myData);
this.loader.addEventListener(Event.COMPLETE, readData);
The readData() method is only called after stopping the audio stream.
Am i missing something obvious here ?
thanks!
Problem W/loaderInfo.loader. INIT Event Not Dispatched.
I have a Flash app made up of AS3 components that I am trying to run in Flex.
In Flash, after the main component is added to the stage, the loader object (loaderInfo.loader) is null which is fine and I handle that.
The same exact code in Flex has different results. On the applicationComplete event I add the the main component to the stage and the loader object's getter throws an exception - Error #2099: The loading object is not sufficiently loaded to provide this information.
Also, the INIT event, which is supposed to be dispatched when the properties and methods of a loaded SWF file are accessible, does not appear to be firing which is probably part of the problem. But I can't figure out why it is not being dispatched.
My code snippet of what happens when the object is instantiated is below.
This line of code in the function checkLoaderInfo(...) throws the exception:
if (this.loaderInfo.loader == null)
The exception is caught in handleAddedToStage(...) which adds handlers as follows...
this.loaderInfo.addEventListener(Event.COMPLETE, checkLoaderInfo);
this.loaderInfo.addEventListener(Event.INIT, checkLoaderInfo);
The events are never dispatched and the Flex app just does nothing after that.
I just get that nice blue flex background...
Code:
public class FluidPlayer extends Container // container is a MovieClip...
{
imports...
private vars...
public vars...
public function FluidPlayer():void
{
if(stage)
handleAddedToStage();
else
addEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
}
private function handleAddedToStage(event:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, handleAddedToStage);
actionsource = new FluidActionSource();
addChild(actionsource);
try
{
checkLoaderInfo();
}
catch (error:Error)
{
this.loaderInfo.addEventListener(Event.COMPLETE, checkLoaderInfo);
this.loaderInfo.addEventListener(Event.INIT, checkLoaderInfo);
}
if (localConnectionName == "")
{
if (ExternalInterface.objectID)
localConnectionName = ExternalInterface.objectID;
else
localConnectionName = "FluidPlayer";
}
if (this.loaderInfo.parameters.hasOwnProperty("listeners"))
{
var listeners:String = this.loaderInfo.parameters.listeners.replace(/s/g,"");
fluidAPI = new FluidAPI(localConnectionName,listeners.split(","));
}
else
fluidAPI = new FluidAPI(localConnectionName);
contentArea = new FluidContentArea();
addChild(contentArea);
fluidController = FluidController.instance;
soundManager = SoundManager.instance;
}
private function checkLoaderInfo(event:Event = null):void
{
this.loaderInfo.removeEventListener(Event.COMPLETE, checkLoaderInfo);
this.loaderInfo.removeEventListener(Event.INIT, checkLoaderInfo);
if (this.loaderInfo.loader == null)
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.addEventListener(Event.RESIZE, handleResize);
handleResize();
if (this.loaderInfo.parameters.hasOwnProperty("XMLData"))
loadXML(this.loaderInfo.parameters.XMLData);
else
trace("* Missing XMLData flashVar, listening for flashLoadXML() API call...");
if (this.loaderInfo.parameters.hasOwnProperty("skin"))
loadStyleSheet(this.loaderInfo.parameters.skin);
else
trace("Missing skin flashVar, listening for flashLoadXML() API call...");
}
}
...
...
Problem W/loaderInfo.loader. INIT Event Not Dispatched.
I have a Flash app made up of AS3 components that I am trying to run in Flex.
In Flash, after the main component is added to the stage, the loader object (loaderInfo.loader) is null which is fine and I handle that.
The same exact code in Flex has different results. On the applicationComplete event I add the the main component to the stage and the loader object's getter throws an exception - Error #2099: The loading object is not sufficiently loaded to provide this information.
Also, the INIT event, which is supposed to be dispatched when the properties and methods of a loaded SWF file are accessible, does not appear to be firing which is probably part of the problem. But I can't figure out why it is not being dispatched.
Any ideas?
Thanks!
Chris
How Do You Listen In One Class For A Custom Event Dispatched From Another Class?
I am not sure how to word this, so here is what I would like to happen:
MyDocumentClass contains an instance of MyItem and MyItemManager. MyItem will fire an ItemEvent.ITEM_CHANGED event. I want MyItemManager to listen and react to that event. Possible? Here's my code:
ItemEvent.as:
ActionScript Code:
package
{
import flash.events.Event;
public class ItemEvent extends Event
{
public static const ITEM_EVENT:String = "itemEvent";
public function ItemEvent(type:String, bubbles:Boolean = false, cancelable:Boolean = false)
{
super(type, true);
}
public override function clone():Event
{
return new ItemEvent(type);
}
public override function toString():String
{
return formatToString("ItemEvent", "type", "bubbles", "cancelable");
}
}
}
MyDocumentClass.as:
ActionScript Code:
package {
import flash.display.Sprite;
import MyItem;
import MyItemManager;
public class MyDocumentClass extends Sprite
{
public var item:MyItem;
public var manager:MyItemManager;
public function MyDocumentClass()
{
item = new MyItem();
manager = new MyItemManager();
item.dispatchCustomEvent();
}
}
}
MyItem.as:
ActionScript Code:
package
{
import flash.display.Sprite;
import flash.events.EventDispatcher;
import ItemEvent;
public class MyItem extends Sprite
{
public function MyItem()
{
}
public function dispatchCustomEvent():void
{
dispatchEvent(new ItemEvent(ItemEvent.ITEM_EVENT));
}
}
}
MyItemManager.as:
ActionScript Code:
package
{
import flash.display.Sprite;
import ItemEvent;
import flash.events.EventDispatcher;
public class MyItemManager extends Sprite
{
public function MyItemManager()
{
addEventListener(ItemEvent.ITEM_EVENT, handleItemEvent);
}
public function handleItemEvent(e:ItemEvent):void
{
// do something here
}
}
}
How To Use SetInterval To Delay Event, Not Just Each Step Of Event
I had some help in setting up this bit of code to fade out a loaded movie:
Code:
function faderFunc() {
_root.holder24._alpha -= 5;
if (_root.holder24._alpha < 0) {
_root.holder24._alpha = 0;
clearInterval(fadeRMS);
}
};
fadeRMS = setInterval(faderFunc, 400);
Trouble is, I am looking to fade the clip slowly to zero once it has been a certain number of seconds, rather than just having the clip fade at a rate of -5 every so many seconds as it is set here.
In comparing this to other code that I have been using setInterval in, I am wondering if the problem is that this setInterval is not control an onEnterFrame event, but rather just control the rate of the alpha fade. I don't see how I could use an on enterFrame with this because the swf has already been loaded into a movie in this same Frame...maybe I am wrong about both of these thoughts, maybe just one.
I would really appreciate some insight on this I have been working with different attempts for a while and cannot get the results I want.
(Here is an example of some other code I am using that does delay the onEnterFrame event, I think, so that the code is not being fully executed until 57 seconds pass...)
Code:
function moveRMS() {
clearInterval(moveRMSInterval);
unloadMovie(_root.holder22);
xstep=(30-holder24._x)/5
ystep =(500-holder24._y)/5
_root.holder24.onEnterFrame = function() {
this._y -= (577-this._y)/ystep;
this._x -= (865-this._x)/xstep;
if (Math.abs(577-this._y)<1 && Math.abs(865-this._x)<1) {
this._y = 577;
this._x = 865;
delete this.onEnterFrame;
}
};
}
moveRMSinterval = setInterval(moveRMS, 57000);
How To Use SetInterval To Delay Event, Not Just Each Step Of Event
I had some help in setting up this bit of code to fade out a loaded movie:
Code:
function faderFunc() {
_root.holder24._alpha -= 5;
if (_root.holder24._alpha < 0) {
_root.holder24._alpha = 0;
clearInterval(fadeRMS);
}
};
fadeRMS = setInterval(faderFunc, 400);
Trouble is, I am looking to fade the clip slowly to zero once it has been a certain number of seconds, rather than just having the clip fade at a rate of -5 every so many seconds as it is set here.
In comparing this to other code that I have been using setInterval in, I am wondering if the problem is that this setInterval is not control an onEnterFrame event, but rather just control the rate of the alpha fade. I don't see how I could use an on enterFrame with this because the swf has already been loaded into a movie in this same Frame...maybe I am wrong about both of these thoughts, maybe just one.
I would really appreciate some insight on this I have been working with different attempts for a while and cannot get the results I want.
(Here is an example of some other code I am using that does delay the onEnterFrame event, I think, so that the code is not being fully executed until 57 seconds pass...)
Code:
function moveRMS() {
clearInterval(moveRMSInterval);
unloadMovie(_root.holder22);
xstep=(30-holder24._x)/5
ystep =(500-holder24._y)/5
_root.holder24.onEnterFrame = function() {
this._y -= (577-this._y)/ystep;
this._x -= (865-this._x)/xstep;
if (Math.abs(577-this._y)<1 && Math.abs(865-this._x)<1) {
this._y = 577;
this._x = 865;
delete this.onEnterFrame;
}
};
}
moveRMSinterval = setInterval(moveRMS, 57000);
Setinterval - Event Handler Help
Help. I need help with code to have this read in as I start my program. I have heard about setinterval, but need help with the code to make it work. Also is this the way on should go?
on (release) {
_root.SQLSelect = "SELECT * from trade WHERE FieldID = 2";
fscommand("flashstudio.selectfromdb", "SQLSelect");
fscommand("flashstudio.getfieldfromdb", ""tradedesc","1",desc2");
fscommand("flashstudio.getfieldfromdb", ""discount","1",discountb");
After An Event. (timer Or SetInterval?)
On frame three of a movie I'm working on I have an alpha fade that takes 3 seconds to complete. Once finished (ie - this._alpha = 0) I want the movie head to go to frame 4.
My alpha fade looks like this on a mc instance:
onClipEvent (load) {
this._alpha = 100;
this.alphaTo (0, 10);
}
That works fine but every attempt of either a setInterval or _root.gotoAndStop(4); either gives me an error or simply goes to frame four without doing the fade first.
Seems pretty simple but I'm lost.
After An Event. (timer Or SetInterval?)
On frame three of a movie I'm working on I have an alpha fade that takes 3 seconds to complete. Once finished (ie - this._alpha = 0) I want the movie head to go to frame 4.
My alpha fade looks like this on a mc instance:
onClipEvent (load) {
this._alpha = 100;
this.alphaTo (0, 10);
}
That works fine but every attempt of either a setInterval or _root.gotoAndStop(4); either gives me an error or simply goes to frame four without doing the fade first.
Seems pretty simple but I'm lost.
SetInterval() Update Event Issue
Hello,
i have a setInterval() on the _root timeline which loads jpeg images in to a movieclip.createEmptyMovie(image,1)
the code is as follows
Code:
Int2 = setInterval(function () { if (i>4) {i = 1;}trace('Int '+i);Url = 'images/flashimages/sequence1_image'+i+'.jpg';eval('ImageEffectMc'+i).Image.image.loadMovie(Url);eval('ImageEffectMc'+i).gotoAndPlay('tween');i++;updateAfterEvent();break;}, 2025);
My problem is while i get images 1 and 2 to appear i am unable to get images 3 and 4 to show.
I made sure all jpegs were NOT progressive = true;
I was able to load the jpegs images perfectly when usng a debug script making sure the movie was created first = true
What could cause it to not show the 3rd and 4th image on setInterval();
Kendall
Problems With SetInterval And MouseDown Clip Event
Ok, odd one this, but I'm having problems using setInterval to call a function from within a mouseDown clip event. The thing is it gets called once but doesnt loop? I cant understand why this would happen because the interval is obviously executing because the function runs once, but doesnt loop as it should. If I define the function from within the setInterval command however it calls the interval correctly and the function loops. I really dont want to do it this way, its much neater having the function elsewhere and besides I have to clear it later on anyway. Anyone else come across this? Is it a bug?
KeyboardEvents Not Being Dispatched?
Hi all, I am having an issue with my current game and the only thing I can conclude is that Flash is simply not dispatching events.
I'm using senocular's Key class for keyboard control. The issue I'm having (note that I've been working on the game for almost 2 months with no issues) is that sometimes the character will get stuck moving in one direction (diagonal if two buttons are down). I'm having a really hard time determining exactly WHAT is causing this, it seems to happen at random. One thing I've concluded though is that I think it happens when there is a bunch of stuff going on at once. All I can think of is that maybe there's so much stuff going on that Flash fails to dispatch KEY_UP events. I have the game check for movement keys on every frame (timer based, not ENTER_FRAME based, although I've tried that too). Has anyone ever had a similar problem?
Listening For Events Dispatched From An Embeded Swf..
I have a main holder SWF into which I load various different pages, all as external content SWFs. Each of these has an init() function to load images/xml etc and a kill() function to remove variables and enterframes etc..
Kill() can only be ran once the page is fully loaded, otherwise it returns errors of null objects etc.. (understandably)
I wish to dispatch an event or trigger something, which the main holder SWF can detect, once the content SWF has fully loaded its content and is ready to be killed..
Can this be done and how?
No MouseEvents Dispatched After Moving A Sprite
Hi all,
i've written a class which extends flash.display.sprite. The objects are then
added to another sprite wich is a child of the Document Class.
When i add them they are initially placed on coord 0/0. On that position,
the mouse events are dispatched correctly.
For some reason though, there are no more events after moving the sprite
somewhere else using mySprite.x = someNewPosition.
The positioning works fine, simply there are no more events dispatched from these objects.
Anyone an idea what i'm doing wrong ?
thanks for your help !
Function Runs When 3 Events Are Dispatched
Hello everybody, I was wondering if it's possible with as3 to run a function when 3 processes are completed. What I mean is that if I have this 3 Objects:
Code:
1. var myloader:Loader = new Loader();
2. var myurlloader:URLLoader = new URLLoader();
3. var myanimator:Animator = new Animato
r();
I have a function named:
Code:
function next_function():void {
trace("it works");
}
I have 3 listeners.
Code:
myloader.contentLoaderInfo.addEventListener(Event.COMPLETE, function1);
myurlloader.addEventListener(Event.COMPLETE, function2);
myanimator.addEventListener(MotionEvent.MOTION_END, function3);
Is there a way that the function just runs once the 3 of the listeners have dispatched the COMPLETE and END events?
Well that's my question, I'm simply trying to learn some AS3 and I was trying to do this but I haven't figured how, any help would be appreciated...
Listening To Events In Subclasses Dispatched From Superclasses
Hello, I'll try to be as clear as possible.
I've two AS2 classes, say Main and Sub.
Sub inherits from Main.
Main gets instantiated by Sub by calling super in its constructor.
In Sub constructor a Main method gets invocated too.
Being this Main method related to a remoting call, it automatically calls a fault or a result event when it receives data from the server.
In the Result function I put:
dispatchEvent({type:'myMessage', target:this});
What I'm trying to do:
this message should be listened by Sub.
When Sub receives this event it should fire one of its methods.
How to do this?
Thanks!
Custom Objects And Internal SetInterval Loops -> A Problem Stopping The SetInterval
Let's say I had a class like this:
PHP Code:
var someVar = new Widget();
function Widget() {
// Some variables, etc...
this.int_someCommand = 0;
// Activate the function on instantiation
this.someCommand();
};
Widget.prototype.someCommand = function() {
clearInterval(this.int_someCommand);
this.int_someCommand = setInterval(this, 'someCommandLoop', 50);
};
Widget.prototype.someCommandLoop = function() {
trace("THIS IS A WIDGET LOOP!");
};
...now, I was always under the impression that if you delete an object in Flash, the setInterval loops associated with it would die as well. But when I try to:
PHP Code:
// At some other point in my timeline...
delete someVar;
or:
PHP Code:
someVar = new Object();
...the original loop is still running (I can tell just by reading the trace). How do I go about properly terminating a setInterval loop inside an Object without having to call a clearInterval()? Or is a clearInterval() the only way?
Thanks.
Tween Class, Does It Use Setinterval? Getting Strange Setinterval Type Problem
I have a gallery with small thumbnails. Upon clicking a thumbnail, I am using the Tween class to pull clips from an array and fade them between each other, loading the clips into a container.
When I click the thumbnail it loads the .swf fine and plays the Tween Class animation just as it's supposed to, however if I click any other thumbnail and go back to that first one the timing gets totally screwed up and the fades get jittery and overlap each other, much like it does with setInterval if you don't clear the intervals.
Is there a way to clear the Tween Class? Does it's timer run on setInterval?
This is the code I am using for the tween class
Thanks!
Code:
import mx.transitions.Tween;
import mx.transitions.easing.*;
//content movieclips put into an array
var mcArray:Array = new Array(content1, content2);
for (var k in mcArray) {
mcArray[k]._alpha = 0;
}
// tween class has something called "OnEnterFrameBeacon" and it is added to the stage
// when we import the as file, so I wanted to get rid of it.
var n:Number = 0;
function playFades() {
if (n<mcArray.length) {
var tween_handler1:Object = new Tween(mcArray[n], "_alpha", Strong.easeIn, 0, 100, 1, true);
tween_handler1.onMotionFinished = function() {
//trace("motion finished by "+mcArray[n]);
//n++;
var tween_handler2:Object = new Tween(mcArray[n], "_alpha", Strong.easeIn, 100, 0, 3.5, true);
tween_handler2.onMotionFinished = function() {
//trace("motion finished by "+mcArray[n]);
n++;
playFades();
};
};
} else {
n = 0;
playFades();
}
}
playFades();
"Clip Changing With "onEnterFrame" Event Now Not Changing With "setInterval.”
Hi,
I have built a simple site where the logo at the top of the page has been constructed as a masked grid, the idea being that the logo is revealed as each cell in the logo has it's color changed.
The color is changed via a tween in each individual cell & I originally triggered this to happen with the following “onEnterFrame” script (newHold_array[k] being the array that holds the clips);
ActionScript Code:
k = 0;_root.onEnterFrame = function() {thisOne = newHold_array[k];this.holdit_mc.nhold_mc[thisOne].play();k++;if (k>=353) {break;}};
The above code works fine but I wanted to speed up the rate of change so put a similar function in to a “setInterval” fired script
ActionScript Code:
function lightUp(){thisOne = newHold_array[k];trace(thisOne);this.holdit_mc.nhold_mc[thisOne].play();k++;if (k>=353) {clearInterval(lightInt)}}
which although firing ok & able to trace out the correct cell with “trace(thisOne);” will not get the correct or any cell to play?
Fla attached.
MovieClipLoader OnLoadInit Event AND Loader Component Complete Event
What´s the difference beetwen the Loader complete event and MovieClipLoader onLoadInit. The manual says onLoadInit is called after the code on the first frame of the loaded clip gets executed, so, it´s better to use onLoadInit if you want to manipulate the loaded asset via code.
So, if anyone could clarify the following points to me, I would be grateful!
- Does the complete event of the Loader component have the same behaviour?
- How does MovieClipLoader knows that the code on the first frame of the loaded assets got executed?
Thanks,
Marcelo.
Custom Event Handlers - Triggering Event Listeners On Other Objects
I'm trying to update an object whenever something happens in another object. At the moment, I have the second object explicitly calling an update function on the first object, but this seems a little sloppy and it strikes me that this is the sort of scenario where I should be using custom event handlers.
I'm not quite sure how they work though. My first assumption is that if I built two objects, one like this which fires off an event:
Code:
public class eventFirer extends Sprite
{
public function eventFirer():void
{
dispatchEvent(new Event("customEvent"));
}
}
...and one like this which updates whenever the custom event happens:
Code:
public class eventListener extends Sprite
{
public function eventListener():void
{
trace ("main");
addEventListener("customEvent", eventFired);
}
private function eventFired(e:Event):void
{
trace ("ok");
}
}
...then eventListener.eventFired would automatically be set off whenever a new eventFirer is created. This seems not to be the case though.
Can anybody enlighten me as to how custom events bubble between otherwise unrelated objects?
Passing Parameters From Event Listener To Event Handler
Hi Chaps,
First of all, apologies as I know this question has been asked before, but I have spent the last twenty minutes reading this thread and still can't seem to figure out how to apply it to my situation - probably because I'm thick!
I have a number of objects which need to be rotated according to different parameters. I have a function which takes those parameters, then uses the tween class to handle the rotation. I'm then using the tweenEvent class to check for when the motion is complete. Then, I need access to those same parameters in the complete handler to do further operations. The problem I have is that the tween event class doesn't allow me to pass the parameters along to the cpmpleteHandler, so I'm stuck getting my parameters from the first function to the second function:
Code:
function rotate(parameters){
rotationTween = new Tween(object,parameter1,parameter2,........);
rotationTween.addEventListener(TweenEvent.MOTION_FINISH,completeHandler);
}
function completeHandler(e:TweenEvent){
//need access to the paremeters passed into the first function here!!
}
From reading the thread mentioned above, I have a feeling I may need a custom class to do this - please don't laugh but I've never written (or had the need to) write my own class before, so I really wouldn't know what to do. Any help greatly appreciated, but an actual code snippet which demonstrates this would be even better!
Ric.
Event Listener Mouse Event Click - Obstructions
This is an oversimplification of my problem.
I have an event listener on a sprite.
I then have portions of this sprite covered with other sprites or moveclips.
If I click a movieclip, it blocks my eventlistener on the sprite underneath it.
Is it possible to listen to the even click 'through' a movieclip. I dont want interaction with them, but I dont want them as bitmap data onto the base sprite either...
I Don't Understand The Keywords: This, Event.target, Event.currentTarget
I am almost a complete beginner to Actionscript 3.0.
I've been looking at tutorials and I now understand most of the basic principles and methods of this programing language (creating basic functions ect..).
However I do not understand the following keywords.
1. this
2. event.target
3. event.currentTarget
What do these words refer to?
How are they different from each-other?
When must i use them?
Event Propagation Vs. Event Blocking -- Confused, Even After Moock
I thought I understood the AS3 event scheme: capture, target, bubbling. That events (e.g. MouseEvents) travel from stage to the object clicked on and then back again, and all objects in the display chain receive and can check that event. But it's also true, it seems, that Interactive Objects in front of others will block and "absorb" events, and those beneath will never hear of the event (unless mouseEnabled for the blocking object is set to false). I don't understand this (seeming) contradiction.
On the Kirupa forums:
Along with event propagation in ActionScript 3 comes different phases of events with display objects. With propagation, you have events being propagated from display objects to other display objects, such as mouse click events being propagated from children to their parents. This lets clicks within children objects to be recognized by parents (since children make up the contents of their parents, its only natural for the parent to also have those same events). The phases of such an event represent the progression of the event as it makes its way through the parent and child objects.
Events actually start with parent objects (phase 1: capturing), starting with the top most parent (stage) and making its way down to the child where the event originated (phase 2: at target). Then after reaching the child it makes its way back up through all the parents again (phase 3: bubbling).
But also:
Though ActionScript 3 now supports event propagation (capturing, bubbling, etc). Events like mouse events still only occur for one specific target for each individual event. In other words, when you click the mouse button over some objects in a Flash movie, only one of those objects is going to recieve the event even though the mouse is physically over other objects as well.…One important thing to keep in mind is that, in ActionScript 3, mouseEnabled is true by default. This means, without any event handlers or listeners used in a movie, every InteractiveObject instance will capture mouse events and prevent them from reaching any other objects beneath them.
Any clarification much appreciated…
The Best Way To Trigger An Event After A Previous Event Has Played.
What would be the best way to trigger an event via button in one movie clip after another event in has played in a different movie clip.
1. Click button in scene 1 on main stage.
2. The background movie (movie2) should scroll the the designated posistion and stop.
3. Then the foreground layer (movie1) should side in over it after the background has scrolled and stop to display information.
Now if you click another button I would like the clip to do this:
1. The foreground layer (movie1) slides back out opposite as it came in.
2. And the the background (movie2) rotates to it's new posistion and stops.
3. The foreground layer slides in same as (movie1) only some other tab and stops.
I'm completely stumped how to do this any help would be greatly appreaciated.
I posted the file here:
http://www.jbowen.com/jbcspage.swf
and
http://www.jbowen.com/jbcspage.fla
If some one could help me out thanks maybe even take a look a the code in the fla document and repost it or explain.
Thanks.
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
ActionScript Code:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
Custom Event Handler For A Timer Event?
I understand how to create custom events in order to pass parameters to a function being called by an event listener. I can get this to work fine if the event is being dispatched within my own code. However, I don't get how to do this if the event is a built-in event being dispatched by a Flash object.
Specifically, I need to call a function and pass it parameters when a timer ends. I don't know how to change the information being sent by the Timer because it is a native Flash class rather than something I'm writing. Can someone please clarify how to do this?
Mouse Event, Event.target Vs Movieclip Name
Hi -
Can anyone help me with a mouse event issue, i'm truly baffled. There's a timer event that loads 4 movieclips (named 'serviceType'), each containing an instance of 2 objects (named 'btn' and 'thumbs'). When clicking on the MC (servicetype) it triggers a mouse event. I'm trying to reference child 'thumbs' of the serviceType MC but in the mouse event function, event.target traces no children, but serviceType traces the 2 children. BUT serviceType only refers to the last instance of serviceType that was loaded in the timer event. Why wouldn't event.target work??
Here's the code, and thanks for the help!!
ActionScript Code:
function loadServices(event:TimerEvent):void {
count = event.target.currentCount -1;
serviceType = new MovieClip;
addChild(serviceType);
btn = new Btn(serviceList, count);
thumbs = new ThumbContainer(count);
serviceType.addChild(btn);
serviceType.addChild(thumbs);
serviceType.addEventListener(MouseEvent.CLICK,loadThumbs);
}
function loadThumbs (event:MouseEvent):void {
trace(serviceType.numChildren); /// Displays 2 (but refers to the last instance loaded)
trace(event.target.numChildren);// Displays 0, why??
}
AS 3 Convert Button Event To Key Enter Event
I'm learning how to use regular expressions in ActionScript 3, and can get an input to be tested by regular expressions, and an answer delivered, if a button is clicked after text is entered.
But darn if I can figure how to code it so they just click the enter key after typing what they like. In the following code punk is a button, and there are two text fields, buzzo the input, and tester the answer to the input. The array questo contains the regular expressions, the array anso contains the responses.
I need code to replace the bottom line with a line that relates to key enter being typed. Thanks for any ideas.
Sally
Attach Code
function makeSense(event:MouseEvent):void
{
tester.text="";
var buzz:String = buzzo.text;
buzzo.text="";
for(i=0;i<questo.length;i++){
if(buzz.search(questo[i])!=-1){
tester.text=anso[i];
}
}
}
punk.addEventListener(MouseEvent.CLICK, makeSense);
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
Using An Event Listeners Function At Will - Event Dispatching?
Hi,
I have a event listener that turns a camera on and off according to how much motion there is:
camera1 = Camera.getCamera(""+Number(aCameraComboBoxes[selComboBoxNum].selectedIndex-1));
aCameras[selComboBoxNum].addEventListener(ActivityEvent.ACTIVITY, activityHandler, false, 0, true);
private function activityHandler(event:ActivityEvent):void {
if(event.activating){
//camera is turning on
}else if (!event.activating){
//camera is turning off
}
}
All of this works but I need a way to rerun the addlistener's function without the camera actual turning on or off. Is there a way for me to use this function, and send it the variable it is looking for?
Thanks
Using Event.target With An Event Handler
Hi folks,
I'm looking for a more efficient way of doing the following:
Code:
function selectLevel():void{
levelSelect.level1.addEventListener(MouseEvent.MOUSE_DOWN,gotoLevel1);
levelSelect.level2.addEventListener(MouseEvent.MOUSE_DOWN,gotoLevel2);
levelSelect.level3.addEventListener(MouseEvent.MOUSE_DOWN,gotoLevel3);
}
function gotoLevel1(e:MouseEvent):void {
currentLevel = 1;
//load up level 1
}
function gotoLevel2(e:MouseEvent):void {
currentLevel = 2;
//load up level 2
}
function gotoLevel3(e:MouseEvent):void {
currentLevel = 3;
//load up level 3
}
As you can probably see, I have a movie clip called 'levelSelect' which contains three buttons - level1, level2 and level3. What I'm doing so far, is adding an event listener to each button, and then if any of them are clicked, it activates a different event handler function for each button.
However, as the only difference in the handler functions is the number of the level, and then assume I have 100 levels, this doesn't seem like very efficient coding!
So, how can I make it so that I have just a single event handler function which all the buttons use, and get it to recognise which level button was clicked? Effectively, I'm trying to do this:
Code:
function selectLevel():void{
levelSelect.level1.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
levelSelect.level2.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
levelSelect.level3.addEventListener(MouseEvent.MOUSE_DOWN,clickHandler);
}
function clickHandler(e:MouseEvent):void {
//somehow detect the level number 'n' from the instance name of the button, or the child number of the parent movieclip
currentLevel = 'n';
//load up level 'n'
}
I'm sure it has something to do with e.target, or e.currentTarget, but I can't get further than that!
Cheers,
Ric.
[CS3] Dispatching An Event From Inside An Event
Does anyone know how to dispatch an event from inside another event?
I get crazy! I have tried a hundred ways to dispatch an event from inside a onLoad event when loading a XML-file. It just doesn't work!!
Here is a simple example:
Code:
class myClass {
public var xmlData;
public var addEventListener:Function;
public var removeEventListener:Function;
public var dispatchEvent:Function;
function myClass() {
xmlData = new XML();
EventDispatcher.initialize(this);
}
function loadXML() {
xmlData.onLoad = function(success) {
if(success){
trace("success");
sendEventLoaded();
}
else trace("Error: Xml not loaded");
}
xmlData.load("filename.xml");
xmlData.ignoreWhite = true;
}
public function sendEventLoaded() { // send the Event
trace("sendEventLoaded()");
dispatchEvent({target:this, type:"isLoaded"});
}
}
The first issue is not dispatching the event itself, but calling the function sendEventLoaded(). It's like it can't be found from within the onLoad event. When the onLoad event occurs, the text "success" is traced, and but the text "sendEventLoaded()" is never executed!!
Does anyone know how to call the sendEventLoaded() from within the onLoad event? Or is there any other way to do this?
I'm thankful for any help I can get!!
Event.COMPLETE Or Event.INIT
I'm working with the loader class. I have a SWF that's loading a presentation in another SWF. The loader swf has a progress bar and perecentage text field. I want the presentation to start playing ONLY when it's 100% loaded. As of now, it starts playing at 10 - 11%.
Here's the code:
ActionScript Code:
var swf:String = "ips_test.swf";
var myURL:URLRequest = new URLRequest(swf);
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.OPEN, initialize);
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, inProgress);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completed);
loader.contentLoaderInfo.addEventListener(Event.INIT, initListener);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioErrorListener);
loader.load(myURL);
function initialize(event:Event):void {
preloader_mc.visible = true;
}
function inProgress(e:ProgressEvent):void {
var percentage:uint = (e.bytesLoaded/e.bytesTotal)*100;
preloader_mc.loader_txt.text = percentage.toString() + "%";
preloader_mc.pbar.scaleX = percentage/100;
}
function completed(event:Event):void {
if(loader.contentLoaderInfo.bytesLoaded == loader.contentLoaderInfo.bytesTotal) {
removeEventListener(Event.OPEN, initialize);
removeEventListener(ProgressEvent.PROGRESS, inProgress);
addChild(loader);
}
preloader_mc.visible = false;
}
function initListener(e:Event):void {
MovieClip(loader.content).play();
}
function ioErrorListener(e:IOErrorEvent):void {
preloader_mc.loader_txt.text = "ERROR";
}
Should I start playing the content of the loader on the INIT or COMPLETE function?
EDIT
Please put code in [ as ] [ /as ] tags (without spaces)
Mouse Event Add Event Listener?
sorry, could not think of a better title!
anyway,
I downloaded a class that perfectly works for me,
it's basically a cube that rotates depending on mouse movement,
the way it does it is with the following line:
spBoard.addEventListener(MouseEvent.MOUSE_MOVE,boa rdMove);
what this does is, whenever the mouse moves the cube moves
the boardMove function does the movement based on the mouse's current position
but what i want to do is the keep the cube moving, if the mouse is on its left, it keeps rotating left, and on its rght, keep rotating right...and preferably to have the speed increase/decrease depending on how far/close mouse is to the center of the cube
any suggestions?
firstly is there an event listener that keeps calling the function just for the mouse 'being there' ? i tried rollover, didn't work
or maybe the boardMove function should be modified? i have no idea how though, totally new to AS3, here's the boardMove function for refrence:
ActionScript Code:
private function boardMove(e:MouseEvent):void {
var locX:Number=prevX;
if(doRotate){
prevX=spBoard.mouseX;
curTheta+=(prevX-locX);
renderView(curTheta);
e.updateAfterEvent();
}
}
AS3: Event.SOUND_COMPLETE Event Not Firing
hey everyone
have a look at the attached code. its not very complex but for some reason i can't get the onPlaybackComplete method to fire. any ideas why? SoundClick is an mp3 in the library set to export as an extension of the Sound class. it plays fine, so presumably extending Sound and accessing its methods is working ok, just cant get that sound_complete event to fire
Attach Code
package ccg.gui {
import ccg.gui.*;
import flash.events.*;
import flash.media.*;
import flash.utils.*;
public class RiderAudio2 {
private var _effectGenericClick:SoundClick;
public function RiderAudio2 ()
{
trace("RiderAudio INIT");
_effectGenericClick = new SoundClick();
_effectGenericClick.addEventListener( Event.SOUND_COMPLETE, onPlaybackComplete );
_effectGenericClick.play();
};
public function onPlaybackComplete ( e:Event ):void
{
trace("RiderAudio onPlaybackComplete ");
};
};
};
Event Listeners VS Event Functions
I'm working on a new project at work where there's lots of custom objects with lots and lots of event listeners. I keep finding myself saying, "why didn't they just use the built in objects with built in event handling?". However, from what I can see it seems like AS3 leans heavily towards using Event Listeners as opposed to putting event responsibility on the object itself (E.G. XML.onload). Is there an advantage to this (other than making it more Java like?) I've always favoured keeping the responsibility on the object itself because it seems like one less object to keep track of and also makes things feel more self contained. If I have 10 objects that fire 10 different events, I have to create 10 different event handlers (or 10 different case statements within the same event handler), whereas with self event handling, I just code in the event function.
Anyways, I wanted to open discussion to which method of event handling you prefer and why, and also what you believe the advantages to this. I was searching google for previous discussions on this but I couldn't seem to find anything, so I thought I'd get the ball rolling! Looking forward to reading these, try not to be too elitist in your posts!!
Can You Initialize A Function With A Event Also Without Event?
For example i have this function:
function doSomething(event:MouseEvent):void {
trace("do a lot of coding...");
}
Now if i want to run the same function as above without the 'click event' on your mouse that does
not seem to be possible.
Is there a work around? Or is the best way to make a in between function like this:
function doManyThings() {
trace("a lot of code here..");
}
function doSomething(event:MouseEvent):void {
doManyThings();
}
Event Dispatcher: Only Receives Event Once
Hey all,
So I have two classes talking to each other with EventDispatcher. One is a thumbnail of an image, and when it's clicked, it sends an event to the other class to display the full size version. I'm using a MovieClipLoader instance to load the full version (and the thumbnail).
Here's how it's sending the event from the thumbnail class:
Code:
private function initButton () {
this.loadMe.onPress = function () {
this._parent.sendEvent();
}
}
private function sendEvent () {
// create eventObject to be passed to anything that is listening
var eventObject:Object = {target:this, type:'onPhotoSelected'};
eventObject.photo2load = this.photoID;
trace ("send Event " + eventObject.photo2load);
// dispatch event that tells any listeners to load the full version
dispatchEvent(eventObject);
}
And here's what's receiving the event:
Code:
public function onPhotoSelected (listenObj) {
trace ("event received");
this.loadPhoto(listenObj.photo2load);
}
public function loadPhoto (photoID:Number) {
trace ("photoID " + photoID);
fullImageLoader.loadClip(this._parent.fullImageURL + this._parent.fileNames[photoID] + ".jpg", this);
}
The problem I'm having is it loads the full size version ONCE. After that, it no longer receives the event. The ("event received") trace no longer comes through. But the ("send event") trace continues to work.
The other weird part is if I comment out the loadClip, then the events come through just fine on both sides. But it's like after it loads an image once, it quits responding to that event ('onPhotoSelected'). Is there some kind of mis-communication between the events of the MovieClipLoader and my custom event or something?
Any theories appreciated!
Event Handlers Vs. Event Listeners
I'm having trouble understanding why listeners are necessary, beyond tying events to objects "conceptually." Are listeners used that often? What am I missing?
|