Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




[as3] Anonymous Function... Remove Listener



Hey what up As3'ers... so I have been under the impression ever since I learned OOp that it is impossible to remove a listener thats callback references a anonymous function.... then a coder at my work started using arguements.callee to approach this. He is getting no runtime errors but is this really freeing the listener appropriatley for garbage collection? I know that you can also use weak references to achieve something similar but I found this fascinating ... any thoughts?


Code:
foo.addEventListner(Event.TYPE, function(event:Event):void {
event.currentTarget.removeEventListener(event.type, arguments.callee);
...
});



ActionScript.org Forums > ActionScript Forums Group > ActionScript 3.0
Posted on: 10-01-2008, 04:06 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

AS3 - Anonymous Functions , Remove Listener...
Hey what up shockers... so I have been under the impression ever since I learned OOp that it is impossible to remove a listener that's callback references a anonymous function.... then a coder at my work started using arguements.callee to approach this. He is getting no runtime errors but is this really freeing the listener appropriately for garbage collection? I know that you can also use weak references to achieve something similar but I found this fascinating ... any thoughts?


Code:
foo.addEventListner(Event.TYPE, function(event:Event):void {
event.currentTarget.removeEventListener(event.type, arguments.callee);
...
});

Cant Remove Event Listener (function In A Function)
I have this function, that when given a movie clip and a destination, it moves it to there, and eases out.

I have buttons that control where it moves to. This all works great.
But I want it so that if it is moving, and a new destination is clicked, it stops and moves to the new destination.

When I remove the event listener, nothing happens. But the event listener removes properly when it stops. (just wont when it is moving)

So the tricky part is this. I have a function in a function, It is there so the moving event:enter_frame parrt can see the same variables passed to it from the click.

If I move this function out of the other function, I can remove it. But it can not access the variables and does not move.

Part that does not work
if (isMoving == true) {// are we moving?
trace('is moving:'+isMoving);
removeEventListener(Event.ENTER_FRAME, mover);// stop moving

PHP Code:



function easeTo(toMove:MovieClip, dest:Number):void {

    trace(toMove +' is being moved to: '+ dest);

    if ( toMove.x  != dest ) {//are we already there? If so, do nothing
        if (isMoving == true) {// are we moving?
            trace('is moving:'+isMoving);
            removeEventListener(Event.ENTER_FRAME, mover);// stop moving
        } else {// not moving, set dest and go.
            trace('is moving:'+isMoving);// reads faluse
            isMoving = true;// now set to true

            addEventListener(Event.ENTER_FRAME, mover);// start moving
        }
    } else {
        trace('we are already there');// do nothing
    }

    function mover(event:Event) {// move. Function here because it needs to access internal varibles
        
        if (Math.abs(dest - toMove.x) < 1) { // are we there? yes? stop event listener
            removeEventListener(Event.ENTER_FRAME, mover);
            isMoving = false;
            wDirection = '';
        } else {
            toMove.x += (dest - toMove.x) * speed;
        }

    }


Remove Mous Listener Function
Hi.. i am doing a tutorial and it's telling me to call the remove mouse listener function.
How do i go about this?

Remove Listener With Custom Function
Hello all!

I have an event listener with a custom function like this:

ActionScript Code:
addEventListener( MouseEvent.MOUSE_UP, function() { doThis( bla ); doThat( bla ); } );

How to remove this? I did a little search but I only get things for normal remove of event listeners..

Thanks!

Anonymous Function & GC
Hi

First post here

I have the following problem. I have one class instance (mediator) which creates and assign children to another (Accordeon).

It looks like that:

Code:
if (_work_center)
_create_list('wkct',
model.getWkct(app_model.currentFactory),
function(item:WKCTVO):String
{ return item.wkct+ ' (' + item.description + ')'; }
);
_create_list:

Code:
private function _create_list(title:String, value:Array, func:Function = null):void {
var canvas:Canvas = _get_new_canvas(title);
var list:List = new List();
_generic_properties(list);
with (list) {
if (func != null)
labelFunction = func;
else
labelField = "description";
...some more properties...
addEventListener(MouseEvent.DOUBLE_CLICK, on_item_doubleclick, false, EventPriority.DEFAULT, true);
addEventListener(DragEvent.DRAG_START, on_list_drag_start, false, EventPriority.DEFAULT, true);
}
canvas.addChild(list);
}
An anonymous function is used for the label. Please note, that this function doesn't use any other variables, except the own parameter

If I remove all references to an instance of this class (mediator) containing these two methods, the instance still retains in the memory and cannot be garbage collected (GC button in profiler doesn't help). I used the profiler to figure it out. What is really interesting, the profiler even doesn't show the object that references this instance - so, it just stay alone.

If i remove this anonymous function or replace it with a static from this mediator class, or the usual function from an accordeon's class, than mediator's instance can be collected and removed.

I thought about anonymous function in this context as it would be a variable. I "create" a function, pass it as a parameter and forget about it. Isn't this like that?

What Exactly Is An Anonymous Function?
Is there a difference between:


ActionScript Code:
advance = function(){...


and


ActionScript Code:
function advance(){...


I believe one of them is known as an anonymous function, but I am not sure which one or why.

Along those same lines... If I am on frame 1 of a movie clip, is there a difference between:


ActionScript Code:
this.advance = function(){...


and


ActionScript Code:
advance = function(){...


Thanks.

What Exactly Is An Anonymous Function?
Is there a difference between:


ActionScript Code:
advance = function(){...


and


ActionScript Code:
function advance(){...


I believe one of them is known as an anonymous function, but I am not sure which one or why.

Along those same lines... If I am on frame 1 of a movie clip, is there a difference between:


ActionScript Code:
this.advance = function(){...


and


ActionScript Code:
advance = function(){...


Thanks.

SetInterval W/ Anonymous Function
Ok, my actual code is much more complicated than this, but I've sheered it down as much as I can. Very little for you guys to look at.


Code:
createEmptyMovieClip("clip", 0);
clip.update = function() {
trace(this);
};
setInterval(clip.update, 500);
Very simply, the trace returns undefined every 500 ms. Calling clip.update() at any time normally and it works completely fine and returns clip. However, called from setInterval, it's giving undefined. You can trace clip.update from the function and that works fine also. So I'm not sure where it's losing the path. This is a rather curious problem... am I missing something obvious?

Anonymous Function Allocation
I really want to not have to reference an instance name in order to get a rollOver function to work on it.

For instance, if I have 1 movieclip on stage, I would simply apply a rollOver event to it.

If I have 10,000 movieclips, this is not realistic. A class or function needs to be written that can target every instance on stage.

I thought that perhaps this would be a mouse event that finds out which movieclip it is over.

I want this function to run on EVERY instance on stage. Anything else will be kept as a graphic or shape so there won't be conflicts.

Please, if anyone can help I'd really appreciate it. I'm sure it just requires a more knowledgable google search, but I'm just not finding the right pages to look at.

Cheers,

Plumper

RemoveEventListener() For An Anonymous Function
I have an event listener with an anonymous function literal, rather than a function reference. What I am trying to figure out is how to remove that event listener.

Obviously, I need a reference to the anonymous function, so the two functions are ===. But, something is going wrong... it just doesn't work, ad this situation doesn't generate any feedback to tell me what might be wrong.

There is some good info here, but not a clear explanation.


Code:
private static var _myFunc:Function;

public static function addCreditsToolTip(clip:DisplayObject):void
{
clip.addEventListener("rollOver",
_myFunc = function():void
{
trace("yay!");
});

trace(_myFunc); //"function Function() {}" < PERFECT!
clip.removeEventListener("rollOver", _myFunc); // < this doesn't work.
}

When Is An Anonymous Function Evaluated?
Hi everyone.

I used two kinds of anonymous function in my AS 3.0 Flash file, in order to implement the roll-over animation of menu buttons. menu_1, menu_2, ... are the buttons already on the stage, and menu_list is an array of them. The code is about adding event listeners on the menu buttons to the corresponding movie clips ("shades" in the code).

It is supposed that when MOUSE_OVER happens on menu_1, then shade_list[0] plays itself from a frame named "colorIn". However, when complied and run, all of the event listeners are linked to the final element of shade_list, namely shade_list[5]. No matter what button your mouse is going over, a shade covers the sixth menu button.

If I put the for statement away and hard-code the whole thing, like menu_list[0].addEventListener( ... ); menu_list[1].addEventListener( ... ); menu_list[2].addEventListener( ... ); ..., then it works fine as I intended. But I'd really appreciate if I can do this with for statement, since this time it should be an extensive menu design.







Attach Code

var menu_list = [menu_1, menu_2, menu_3, menu_4, menu_5, menu_6]
var shade_list = new Array
for (var menuNumber in menu_list)
{
shade_list.push(new menuBoxShade)
shade_list[menuNumber].x = menu_list[menuNumber].x
shade_list[menuNumber].y = menu_list[menuNumber].y
addChild(shade_list[menuNumber])
menu_list[menuNumber].addEventListener(MouseEvent.MOUSE_OVER, function (MouseEvent) { shade_list[menuNumber].gotoAndPlay("colorIn") })
menu_list[menuNumber].addEventListener(MouseEvent.MOUSE_OUT, function (MouseEvent) { shade_list[menuNumber].gotoAndPlay("colorOut") })
}

RemoveEventListener() For An Anonymous Function
I have an event listener with an anonymous function literal, rather than a function reference. What I am trying to figure out is how to remove that event listener.

Obviously, I need a reference to the anonymous function, so the two functions are ===. But, something is going wrong... it just doesn't work, ad this situation doesn't generate any feedback to tell me what might be wrong.

There is some good info here, but not a clear explanation.


Code:
private static var _myFunc:Function;

public static function addCreditsToolTip(clip:DisplayObject):void
{
clip.addEventListener("rollOver",
_myFunc = function():void
{
trace("yay!");
});

trace(_myFunc); //"function Function() {}" < PERFECT!
clip.removeEventListener("rollOver", _myFunc); // < this doesn't work.
}

Anonymous Function Syntax AS2 To AS3
I'm trying to change an anonymous function that was written in AS2 to AS3 but I'm having some problems.

AS2 Code:

Code:
var gridView:GridView = GridView(
this.attachMovie('gridViewMC', 'gridView', this.getNextHighestDepth(),
{width:550, height:350, _lineSpacing:10, _zoomFactor:1,
_x:Stage.width-560, _y:10,
defaultPieceWidth:150, defaultPieceHeight:150,
maxPieceWidth:250, maxPieceHeight:250}));

AS3 Code:

Code:
var gridView = function(
this.attachMovie('gridViewMC', 'gridView', this.getNextHighestDepth(),
{width:550, height:350, _lineSpacing:10, _zoomFactor:1,
_x:Stage.width-560, _y:10,
defaultPieceWidth:150, defaultPieceHeight:150,
maxPieceWidth:250, maxPieceHeight:250}));
Thanks!

Anonymous Function Scope Disaster
I have 2 examples to show...

#1 (works)...

Code:
var i:int = 3;
var f:Function = function () {
var i:int = 5555;
trace(i); // traces '5555'
}
trace(typeof f); // traces 'function'
f();
#2 (problem)...

Code:
var i:int = 3;
var f:Function;
f = function () {
var i:int = 5555; // gives ReferenceError: Error #1056: Cannot create property ::i on global.
trace(i); // this line is never reached
}
trace(typeof f); // traces 'function'
f();
Notice the comments in #2. Why doesn't #2 work? Look closely and see, the only difference is that I moved the assignment of 'f' to the next line, instead of the same line where it is declared as being a Function. But for some reason, f() in #2 thinks its own scope exists in the place where "var i:int=3" is declared, so the function fails and brings Flash to its knees!!! I need #2 to work, because I assign anonymous functions to an Object instance that I pass around. It is the style of coding I have used in Flash for years

I thought AS 3.0 allowed anonymous functions as a genuine courtesy to the AS 1/2 crowd to ease the transition to its forced 100% external class-based stuff. But I am worried I have encountered a bug that delivers a fatal blow to my coding style ... ???

Someone please show me I am wrong...

Anonymous Function – Return Values
Hello, I will appreciate any help with this problem; let me describe a little bit what I’m trying to do:

I have 2 SWF, one.swf and two.swf
1 LocalConnection to send 1 variable from one.swf to two.swf


one.swf code:

var param:Number = new Number(5);

var sending_lc:LocalConnection = new LocalConnection();
sending_lc.send("_Connection1", "myMethod", param);


two.swf code:

this.createTextField("text1_txt", 1, 20, 20, 100, 20);
texto1_txt.border = true;

var receiving_lc:LocalConnection = new LocalConnection();
receiving_lc.connect("_Connection1");
receiving_lc.myMethod = function (param:Number){
text1_txt.text = param; //just to test values
temp = param;
};

// I need to do this
Switch (“param value”) {
….
}

This code actually works pretty well sending the “ param ‘ from one.swf to two.swf

Problem:

I need to be able to use “param” value out of the function, because a I need to perform a switch with this value, since the function wich receives de “param” value is an anonymous function I don’t know how to do to get the value from outside the function because a don’t have a reference name to the function so, the normal way to return a value is not going to do the job.

I will appreciate any help, thanks

Remove Listener
Will removing a listener improve player performance?

Remove Listener
I have an input text and a button. After I press the button, the listener disappears in the debugger, but it still traces the Enter key press. Why is that? I want it to stop checking for the key press.


ActionScript Code:
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
    if(Key.isDown(Key.ENTER)){
        trace("Pressed Enter");
    }
}
Key.addListener(keyListener);


my_btn.onRelease = function(){
    trace("Remove Listener");
    _root.Key.removeListener(keyListener);
    delete keyListener;
};

[F8] How Do I Remove A Listener Object?
I have created a listener object this way:

_root.cmbCatListener = new Object();


Code:
_root.cmbCatListener.change = function(evt_obj:Object):Void {
// do something
}
How do I remove that?

I tried:


Code:
_root.cmbCatListener.removeListener(this);
_root.cmbCatListener = undefined;
No one worked, and the listener still keeps there.

Thanks.

Mouse Listener - Can't Remove - Help
Here is the code I am using. In following frames it still is registering the mouse down for the mouse listener. How do I remove it? Thanks for your help in advance!

this.mouseListener = new Object (this);
this.mouseListener.onMouseDown = function () {
if (this.rightClick_mc.hitTest(_root._xmouse, _root._ymouse, true) != true) {
this.gotoAndPlay(69);
}
}
this.mouseListener.onMouseUp = function () {
this.Mouse.removeListener(this.mouseListener);
}

Remove A Listener Good Or Bad?
Hi!

Working with lots of FLV´s in a separate movieClip placed in separate keyframes.
Each of the FLV´s have a addEventListener trigging other movieClips from their own unique
cue points.

Is it good programming practice to use the removeEventListener from each FLV after completing their task?
Does a lot of Listeners still running lagg the Player?
Or does the Listener removes itself when the FLV is replaced by a new FLV with a new Listener in a new keyframe.


I hope 2007 still feels crispy and fresh for all you Flashers as it feels for me

Remove(?) Listener For TimerEvent.TIMER_COMPLETE
If i am listening for a TimerEvent.TIMER_COMPLETE as I wrote below:

Code:
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE,myFunction);
Do I need to invoke removeEventListener() in the myFunction ??

Remove Event Listener Until Another Mc Is Clicked
Here is my current code. I want to removeEventListener until this button has been clicked (mc_altogether.mc_imac.mc_backdesk.) How would I code that in?



Code:
mc_altogether.mc_imac.addEventListener(MouseEvent.CLICK,imacin);

function imacin(e:Event):void {
mc_altogether.mc_imac.gotoAndPlay(10);

mc_altogether.mc_imac.removeEventListener(MouseEvent.CLICK, imacin);


mc_altogether.mc_imac.mc_backdesk.addEventListener(MouseEvent.CLICK,imacout);

function imacout(e:Event):void{
mc_altogether.gotoAndPlay(15);

mc_altogether.mc_imac.mc_backdesk.removeEventListener(MouseEvent.CLICK, imacout);
}
}

Is it just a case of adding the EventListener again? If so where? I've tried a few things, not got it to work as yet.

Remove Child From Event Listener
ok I have a game that at a certain point starts to omit particles, I give them motion through an event listener called moveParticles, however whenever I try to remove them from the display list, my program crashes,

ActionScript Code:
//EMITS PARTICLES
public function addParticles(x,y){
var particle:MovieClip;

for(var i:int = 0; i < 200; i++){
particle = new MovieClip();
randomParticleX = Math.random() * 60 - 30;
randomParticleY = Math.random() * 60 - 30;
particle.movementX = randomParticleX;
particle.movementY = randomParticleY;
particle.x = x;
particle.y = y;

particle.graphics.lineStyle(1);
particle.graphics.beginFill(0xFFFFFF);
particle.graphics.drawCircle(0,0,2);
particle.graphics.endFill();
particle.addEventListener(Event.ENTER_FRAME,moveParticles);
particles.push(particle);
addChild(particle);

}
}
public function moveParticles(evt:Event){
var thisParticle = (evt.target as MovieClip);
thisParticle.x += thisParticle.movementX;
thisParticle.y += thisParticle.movementY;
if(evt.target.x >= 1000 || evt.target.x <= 0 || evt.target.y >= 900 || evt.target.y <=0){
removeChild(thisParticle);
}
}

How To Remove And Restore Event Listener Correctly
Hi,

Sorry if this is long-winded but I'll try explain what I'm trying to achieve..

I've a main movie on stage (called sciRoom) which I have following event listener to navigate with:
stage.addEventListener(KeyboardEvent.KEY_DOWN, navMovie); - navMovie uses keys to nav forward and back on sciRoom..

When button is pressed on sciRoom movie, a loaded swf (called phoneMov) pops up by being added to stage..this contains a small puzzle..when this is exited, I remove it from stage and so am back to my original movie. This all works well except that the above event listener to navMovie seems to be dropped(for want of better word)..even though I've tried to explicitly add it back. However, if I click on the stage with mouse it starts to work again(??).

Anyone know why this is so?.. Or how to avoid/correct this so that I don't have to click back on stage with mouse first?

Code:
stage.addEventListener(KeyboardEvent.KEY_DOWN, navMovie);

phoneBtn = sciRoom.btn_mc;
phoneBtn.addEventListener(MouseEvent.CLICK, playPhone);

//load phone swf
function playPhone(e:Event){

var myrequest2:URLRequest = new URLRequest("telephone.swf");
var myloader2:Loader = new Loader();
myloader2.load(myrequest2);
myloader2.contentLoaderInfo.addEventListener(Event .COMPLETE, phLoaded);

}

//add phoneMov to stage and turn off event listeners
function phLoaded(e:Event):void{

phoneMov = e.target.content;
stage.addChild(phoneMov);

phoneMov.x = 190;
phoneMov.y = 200;
phoneMov.scaleX = .8;
phoneMov.scaleY = .8;
sciRoom.alpha = .5;
stage.removeEventListener(KeyboardEvent.KEY_DOWN, navMovie);
phoneBtn.removeEventListener(MouseEvent.CLICK, playPhone);

hangUp = phoneMov.redHolder;
hangUp.addEventListener(MouseEvent.CLICK, quitPhone);

}

//remove phoneMov and restore Ev Listener on stage
function quitPhone(e:Event){

stage.removeChild(phoneMov);
sciRoom.alpha = 1;
stage.addEventListener(KeyboardEvent.KEY_DOWN, navMovie);
phoneBtn.addEventListener(MouseEvent.CLICK, playPhone);


}

Remove Event Listener After Innitial Swf Loads
Hi,

I'm new to as3 but I have a project where 9 buttons call 9 external swfs to the stage into a container. However, I want to have the "movie01.swf" play when the main swf is loaded. I don't know how to get "movie01.swf" to play only once.
I figure i need to remove the eventListener but I know what I have below is wrong. (only button01 is included here so you have an idea of what I'm doing).

Thanks in advance.


Code:


container.addEventListener(Event.ENTER_FRAME, loadmc);


function loadmc(e) {
   var request:URLRequest=new URLRequest("movie01.swf");
   var loader:Loader = new Loader();
   loader.load(request);

   container.addChild(loader);
   var containerTween:Tween=new Tween(container,"alpha",Regular.easeInOut,0,1,6);
}

container.removeEventListener(Event.ENTER_FRAME, loadmc);

var b1tween:Tween=new Tween(button01,"alpha",Regular.easeInOut,.3,.3,1);

button01.addEventListener(MouseEvent.CLICK, b1click);
function b1click(e) {
   var request:URLRequest=new URLRequest("movie01.swf");
   var loader:Loader = new Loader();
   loader.load(request);

   if (container.numChildren) {
      container.removeChildAt(0);
   }

   container.addChild(loader);
   var containerTween:Tween=new Tween(container,"alpha",Regular.easeInOut,0,1,6);
}

button01.addEventListener(MouseEvent.MOUSE_OVER, b1over);
button01.addEventListener(MouseEvent.MOUSE_OUT, b1out);
function b1over(e) {
   b1tween.continueTo(1, 12);
}

function b1out(e) {
   b1tween.continueTo(0.3, 12);

Remove Event Listener Until Another Movieclip Is Clicked
Here is my current code. I want to removeEventListener until this button has been clicked (mc_altogether.mc_imac.mc_backdesk.) How would I code that in?

Code:

mc_altogether.mc_imac.addEventListener(MouseEvent.CLICK,imacin);

function imacin(e:Event):void {
mc_altogether.mc_imac.gotoAndPlay(10);

mc_altogether.mc_imac.removeEventListener(MouseEvent.CLICK, imacin);


mc_altogether.mc_imac.mc_backdesk.addEventListener(MouseEvent.CLICK,imacout);

function imacout(e:Event):void{
mc_altogether.gotoAndPlay(15);

mc_altogether.mc_imac.mc_backdesk.removeEventListener(MouseEvent.CLICK, imacout);
}
}

Is it just a case of adding the EventListener again? If so where? I've tried a few things, not got it to work as yet.

Listener Function?
Can anyone help me, i am looking for a tutorial on the listener funtion, i want to apply it when a variable changes...
A link would be greatly appriciated

Listener Function Cleanup
Hi I can someone clean up, and optimize this function for me? It works perfectly but it just seems like it could have a bit more capability or be a little sleeker.

One thing I would like is the clip var to refer to an actual object (Maybe back to the movieclip that referred it).

W N E S are the corresponding borders on the screen.
^N | Sv
<W | E>


Code:
function watchMouseAreaWNES(clip,W,N,E,S){
var mouseListenerOutside:Object = new Object();
mouseListenerOutside.onMouseMove = function() {
if(_xmouse <= W or _xmouse >= E or _ymouse <= N or _ymouse >= S) {
clip.play();
Mouse.removeListener(mouseListenerOutside);
}
}
Mouse.addListener(mouseListenerOutside);
return true;
}


-By the way this is a listener function that looks for the mouse OUTSIDE the rectangle. Pretty handy.

The below watches the area INSIDE the coordinates:

Code:
function watchMouseAreaInsideWNES(clip,W,N,E,S){
trace("ADDED");
var mouseListenerInside:Object = new Object();
mouseListenerInside.onMouseMove = function() {
if(_xmouse >= W and _xmouse <= E and _ymouse >= N and _ymouse <= S) {
clip.play();
Mouse.removeListener(mouseListenerInside);
}
}
Mouse.addListener(mouseListenerInside);
return true;
}

Listener Function Question
if i have:


PHP Code:



myListener.cuePoint = functionName; 




and then i want to change the function associated,


PHP Code:



myListener.cuePoint = functionName2; 




doesn't seem to override it, do i need to delete something and start over, or is there a proper way to make this work?

scott

Listener Run My Function 2 Times
Hello, I hope I could get some help with this issue, since I give up. It is too much for just me.
This script is originally from MX. I have a hard time trying to translate to AS3.
Anyway. There were a moment when I have to mix the original code with the slide show tutorial from kirupa site. Right now is almost functional. But it behave very weird when is online.
My problem is this. After all the work my final touch is to place a preloader to each loaded image(I already made it). But the secuence should be IF LOADED...then execute the FX and summ 1 number to the secuence...
At the end everything works OK, locally, but online the process show the previous images before it get to the preloader secuence of the new comming image. Becouse of this I step a few test behind the actual and noted this:
When the user see the first set of images, everything is OK, but if he move to other, then the listener seem to execute the click function 2 times, becouse the trace window show 2 outputs. At the end we have the right number, but I don't know if this is the problem.
I'm placing the file here, since it seem to be a little big to post here, and the code is very long.
http://bengalamedialab/forums/album_trace_error.zip

One more thing, I hope someone could help me becouse this is a very diferent kind of gallery file, and I think it could be usefull to others. It has some interesting funtionalities, but I have to solve this small problem before I could place it for the public use. And there aren't many in AS3.

Watch Function In AS 3.0? Probably A Listener...
Hey folks,

I am trying to run a function I use to use in AS 2 but I need some help converting to AS 3 as it is a watch function. Here's the code, see my comments,


ActionScript Code:
//This is called from a custom class, no need to change this part it works.
scorm.get("cmi.core.student_name,studentObject.theName");

// Add a property for name.. no problem works fine
studentObject.theName = "None";

// Write the callback function to be executed if the property changes
// Not sure if I can declare this like this... wasn't giving me an error in AS 3.0
var studentNameWatcher:Function = function(prop, oldVal, newVal) {
    var firstname:String = newVal.toString();
    var my_array:Array = firstname.split(" ");
    for (var i = 0; i<my_array.length; i++) {
}
welcome.nameHolder.text = my_array[1];
}

// I probably need a listener, rather than a watch but I am not sure what exactly I need to put here
studentObject.watch("theName", studentNameWatcher);

//Thanks for the help :)

Event Listener Function
I am wondering if there is anyway to pass a value with the function in an event listener function.

Code:
function finished(f_clip) {
trace("hit");
f_clip._visible = false;
}
one.addEventListener("complete", finished(one));
I have a couple FLV's on the canvas and I'd like call ONE function when they are each finished playing, but have clip specific code executed.

Call Function Outside Of A MCL Listener.onload
i have a movie clip loader object set up and want to call a function from a movieclip out side of the MCL see code below:

to call it normally just startloading(); would do it right? but if it is in a listener.onloadProgress can it be done?




Code:
var myMCL:MovieClipLoader = new MovieClipLoader();
var myListener:Object = new Object();
myMCL.addListener(myListener);

myListener.onLoadProgress = function(target_mc:MovieClip, loadedBytes:Number, totalBytes:Number) {
preload_mc.play(); // play the animation here

// this is the function i want to call from the preload_mc when it reaches a frame.
function startloading(){
trace("startloading called");
}
}
}

Event Listener For A Function Return
Hey All,
I am wondering if there is a way to have an EventListener listen for the return of from a class? I am also wondering if I am going about thinking about this the right way. Here is my code:

This snippet creates a splash screen:

PHP Code:



public class Main extends MovieClip {
function splashScreen() {
            var mainSplash:Splash = new Splash //This is my splash screen class
            addChild (mainSplash) //adds the main splash graphic
        }
}




And this is the Splash Class

PHP Code:



package roids {
    
        import flash.display.*;
        import flash.events.*;
        import flash.ui.*
        
    public class Splash extends MovieClip {
        public function Splash() {
            trace ("Splash Initialized")
            
            //Creates a button to start the program
            var mainStartButton:MainButton = new MainButton
            addChild(mainStartButton)
            mainStartButton.x = 275
            mainStartButton.y = 300
            mainStartButton.addEventListener(MouseEvent.CLICK, buttonClicked)
            
        }
        function buttonClicked(event:MouseEvent){
            /* what can I put here to return to the parent that a button has been clicked?*/
            
        }
    }
}




In essence I want the main class to know that the mainSplash is returning that the mouse was clicked. Whats the best way to do this?

Event Listener Won't Call Function
I'm trying to build a project from within AS2.0 classes as opposed to the timeline. But I can't get event functions to call other functions.

Here's a simplified view of my project problem: (I've supplied an example .zip with .fla, dummy .xml and enclosing folder)

Code:
class MyClass extends MovieClip{
var myData:XML;
function loadData(file:String){
myData = new XML();
myData.ignoreWhite = true;
myData.onLoad = function(success){
trace("onLoad reached");
if(success){
trace(file+" acquired");
myFunction(); // How can I get this to work?
} else {
trace("couldn't load "+file);
}
}
trace("loading "+file);
myData.load(file);
}
function myFunction(){
trace(myData.toString());
}
}
myFunction never gets called because as soon as Flash enters the event function it loses focus of where it is (which kinda defeats the idea of OOP).

Is there a way around this or am I stuck building projects on the timeline?

Passing Parameters Of The Function With The Listener
my function is this:

ActionScript Code:
function gotoAndPlayRandomFrameLabel(clip_name, frameLabels_array) {
    if (frameLabels_array == undefined) {
        frameLabels_array = clip_name.frameLabels;
    }
    var randomLabel:Number = Math.floor(Math.random() * (frameLabels_array.length));
    clip_name.gotoAndPlay(frameLabels_array[randomLabel]);
}


and my timer is this:

ActionScript Code:
var blink_interval:Timer = new Timer(5000);
blink_interval.addEventListener(TimerEvent.TIMER, MovieClip(parent).gotoAndPlayRandomFrameLabel(this.head_mc.blink_mc, this.head_mc.blink_mc.frameLabels));
blink_interval.start();

I'm getting a Error #2007: Parameter listener must be non-null.

How can I pass the parameters with the timer to the function? Make sense?

Dynamic Listener And Handler Function
Hi guys,
AS3 thing, heaving problems with getting this thing to work.
Basically I am trying to create a dynamic function ie. the dynamic name of a function.

I am loading xml file with links in it ex. <link_01>url</link_01>...
then for loop, where a button (acctually a mc, but behaves as one) for each url is created:


ActionScript Code:
for (var i:uint = 0; i<xmlData.*.length(); i++)
linkButton = new linkButton_mc();
linkButton.name = "linkButton_"+ (i + 1);

var inst:String = linkButton_001.name;

next I want to add to each of those mcs a listener, so in this same iteration. (It needs to be dynamic, so I found out earlier that you need to use [] to use a string as a dynamic variable name, so that each dynamically created button gets its own dynamic listener)


ActionScript Code:
[inst]addEventListener(MouseEvent.MOUSE_OVER,overFunction);
function boldFunction(e:MouseEvent):void{
     [inst]overShape_mc.visible = false;
     [inst]outShape_mc.visible = true;

     [inst]addEventListener(MouseEvent.MOUSE_OUT,regularFunction);
     function regularFunction (e:MouseEvent):void{
          [inst]overShape_mc.visible = true;
          [inst]outShape_mc.visible = false;

     };
};

But now I am getting only the last button to display roll over/out states, even when I roll over the first button the roll over state shows up only at the last button.

I tried to make those handler functions dynamic:

ActionScript Code:
var overFunction:String = "on"+inst+"_Over";
var outFunction:String = "on"+inst+"_Out";

[inst]addEventListener(MouseEvent.MOUSE_OVER, [overFunction]);
function [overFunction](e:MouseEvent):void{
     [inst]overShape.visible = false;
     [inst]outShape.visible = true;
....

...but the [] trick doesn't work. What I get is:
1084: Syntax error: expecting identifier before leftbracket.

Is there any way of creating dynamic functions? Or do you have any other ideas to go round the need of using dynamic function names?
cheers

How To Call A Function With More Than One Parameter From A Listener
How can I pass more than one argument with a listener ?


ActionScript Code:
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, myMethodName);

I would like to have

myMethodName(my parameter);

thanks

Function - Listener Event On Mc Collision
is it possible to use a listener or something to trigger a function when 2 mc's collide?

Global Access To Listener Function
Hello All --

I am using a third-party Flash add-on tool that will let me get a device's battery level (among other things) via listeners. The following code is in my first actionscript frame:

-------------------------------------------------------------
import ssp.device.*;
var statusListener:Object = new Object();

// set-up status listener to get battery level
statusListener.getBatteryLevel = function(e)
{
_global.batteryLevel = e;
}

Status.addEventListener(statusListener);
Status.getBatteryLevel();
-------------------------------------------------------------

The final line in the preceding script successfully sets _global.batteryLevel. The problem is that the script is run only once, when the application starts. What I need to be able to do is to call Status.getBatteryLevel() from a battery monitoring movieclip within my main movie. The movieclip runs constantly to update a display of remaining battery charge.

Unfortunately, whenever I try to execute Status.getBatteryLevel() from any frame other than the one where the listener is set-up, the function does not work. Is there something that I need to do to make the function call available globally?


Regards,


-- Phil

Event Listener Modular Function
hey guys, i am building my website and am trying to make my button functions modular. Right now i have the rollover effect working the way i want with this code...

function onResumeOver(evt:MouseEvent):void {
resume_btn.gotoAndPlay("over");
};

resume_btn.hit_area_mc.addEventListener(MouseEvent .ROLL_OVER,onResumeOver);

function onResumeOut(evt:MouseEvent):void {
resume_btn.gotoAndPlay("out");
};

resume_btn.hit_area_mc.addEventListener(MouseEvent .ROLL_OUT,onResumeOut);

But when i tried to make it modular for the otehr buttons im having errors with this code...


function buttonOver(button:MovieClip, evt:MouseEvent):void {
button.gotoAndPlay("over");
}

buttonOver(profile_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOver));
buttonOver(downloads_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOver));
buttonOver(resume_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOver));
buttonOver(contact_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOver));

function buttonOut(button:MovieClip, evt:MouseEvent):void {
button.gotoAndPlay("out");
}

buttonOut(profile_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOut));
buttonOut(downloads_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOut));
buttonOut(resume_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOut));
buttonOut(contact_btn.hit_area_mc, addEventListener(MouseEvent.ROLL_OUT,buttonOut))

Does anyone see where my problem is? and or a solution.

Thanks

AS3 - Dynamic Listener And Handler Function
Hi guys,
AS3 thing, heaving problems with getting this thing to work.
Basically I am trying to create a dynamic function ie. the dynamic name of a function.

I am loading xml file with links in it ex. <link_01>url</link_01>...
then for loop, where a button (acctually a mc, but behaves as one) for each url is created:

ActionScript3 Code:

Code:
for (var i:uint = 0; i<xmlData.*.length(); i++)
linkButton = new linkButton_mc();
linkButton.name = "linkButton_"+ (i + 1);

var inst:String = linkButton_001.name;
next I want to add to each of those mcs a listener, so in this same iteration. (It needs to be dynamic, so I found out earlier that you need to use [] to use a string as a dynamic variable name, so that each dynamically created button gets its own dynamic listener)

ActionScript3 Code:

Code:
[inst]addEventListener(MouseEvent.MOUSE_OVER,overFunction);
function boldFunction(e:MouseEvent):void{
[inst]overShape_mc.visible = false;
[inst]outShape_mc.visible = true;

[inst]addEventListener(MouseEvent.MOUSE_OUT,regularFunction);
function regularFunction (e:MouseEvent):void{
[inst]overShape_mc.visible = true;
[inst]outShape_mc.visible = false;

};
};
]
But now I am getting only the last button to display roll over/out states, even when I roll over the first button the roll over state shows up only at the last button.

I tried to make those handler functions dynamic:
ActionScript3 Code:

Code:
var overFunction:String = "on"+inst+"_Over";
var outFunction:String = "on"+inst+"_Out";

[inst]addEventListener(MouseEvent.MOUSE_OVER, [overFunction]);
function [overFunction](e:MouseEvent):void{
[inst]overShape.visible = false;
[inst]outShape.visible = true;
....
...but the [] trick doesn't work. What I get is:
1084: Syntax error: expecting identifier before leftbracket.

Is there any way of creating dynamic functions? Or do you have any other ideas to go round the need of using dynamic function names?
cheers

AS3 - Dynamic Listener And Handler Function
Last edited by anyuser : 2008-10-01 at 07:33.
























Hi guys,
AS3 thing, heaving problems with getting this thing to work.
Basically I am trying to create a dynamic function ie. the dynamic name of a function.

I am loading xml file with links in it ex. <link_01>url</link_01>...
then for loop, where a button (acctually a mc, but behaves as one) for each url is created:


Code:
for (var i:uint = 0; i<xmlData.*.length(); i++)
linkButton = new linkButton_mc();
linkButton.name = "linkButton_"+ (i + 1);

var inst:String = linkButton_001.name;
next I want to add to each of those mcs a listener, so in this same iteration. (It needs to be dynamic, so I found out earlier that you need to use [] to use a string as a dynamic variable name, so that each dynamically created button gets its own dynamic listener)


Code:
[inst]addEventListener(MouseEvent.MOUSE_OVER,overFunction);
function boldFunction(e:MouseEvent):void{
[inst]overShape_mc.visible = false;
[inst]outShape_mc.visible = true; [inst]addEventListener(MouseEvent.MOUSE_OUT,regularFunction);
function regularFunction (e:MouseEvent):void{
[inst]overShape_mc.visible = true;
[inst]outShape_mc.visible = false;
};
};
But now I am getting only the last button to display roll over/out states, even when I roll over the first button the roll over state shows up only at the last button.

I tried to make those handler functions dynamic:


Code:
var overFunction:String = "on"+inst+"_Over";
var outFunction:String = "on"+inst+"_Out";

[inst]addEventListener(MouseEvent.MOUSE_OVER, [overFunction]);
function [overFunction](e:MouseEvent):void{
[inst]overShape.visible = false;
[inst]outShape.visible = true;
....
...but the [] trick doesn't work. What I get is:
1084: Syntax error: expecting identifier before leftbracket.

Is there any way of creating dynamic functions? Or do you have any other ideas to go round the need of using dynamic function names?
cheers

Remove Function
Hi everybody,
i have a square that can be moved with the arrows and every 5 seconds a camera capture switches on.
Now I want the camera to display the image for 3 seconds and switch back tp the square.
cant firgure out how to do this. Any ideas?
Thanx in advance

Remove Function
Hi everybody,
i have a square that can be moved with the arrows and every 5 seconds a camera capture switches on.
Now I want the camera to display the image for 3 seconds and switch back tp the square.
cant firgure out how to do this. Any ideas?
Thanx in advance

Remove Function?
Hi there!

I want to remove function from stage.

Working in Flash IDE CS4:

ActionScript Code:
function test():void { trace("bump"); }

// attempt to remove properly
// OUTPUT: "1168: Illegal assignment to function test."
this.test = null;


// attempt to delete (old as way?)
// OUTPUT: "1189: Attempt to delete the fixed property test.  Only dynamically defined properties can be deleted."
// ALSO OUTPUT: "Warning: 3600: The declared property test cannot be deleted. To free associated memory, set its value to null."
delete test;

how to remove it? 2nd idea points me to 1st idea which points me to ERROR .
Aslo, im in IDE and i cant define dynamic function on timeline

Problem Returning A Value From A Listener To Calling Function
hello all,

i cannot seem to get the value (true/false) back to the calling function, btnAdd, from the WS connector listener. here is the code:

code: //handler for Add button for Designations
btnAdd.onPress = function(){
//first, validate the AgencyCode against the Db
var okToAdd:Boolean = false;
okToAdd = validCode(code_txt.text); //call the method, passing a string
/************************************************** ***************************/
trace("in mainProgr: " + okToAdd); //this is THE PROBLEM, D/N/W, "undefined"
/************************************************** ***************************/
//if code is valid, augment the Designations array
if(okToAdd == true) { //i cannot get this to show true or false!
desigData.push({Code:code_txt.text, Amount:amount_txt.text});
//desig_lst.get properties for headings later
viewListBox();
//reset fields
code_txt.text = "";
amount_txt.text = "";
} else {
//cancel the action, show msg, reset fields
Alert.show("Please enter a valid code.", "Invalid Agency Code");
code_txt.text = "";
amount_txt.text = "";
code_txt.setFocus;
}
}
function viewListBox() {
desig_lst.dataProvider = desigData; //awol now
grdDesig.dataProvider = desigData; //changed to dg
}
function createArray() {
desigData = new Array();
}

function validCode(agcyCode:String) {
//called by btnAdd, works like an authenticate user
//write the remote call to the web service method
var valCodeWSconn:WebServiceConnector = new WebServiceConnector();
valCodeWSconn.WSDLURL = "http://www.newmediavisions.com/clients/esd/designationsWS.cfc?wsdl";
valCodeWSconn.operation = "validateCode";
valCodeWSconn.params = [agcyCode]; //this is the code to be looked up
valCodeWSconn.multipleSimultaneousAllowed = false;
valCodeWSconn.suppressInvalidCalls = false;
var trueOrFalse:Boolean
valCodeWSconn.addEventListener("result", wsListener); //for result
valCodeWSconn.addEventListener("status", wsListener); //in case of errors
valCodeWSconn.trigger();
}

//was in the .as file
var wsListener:Object = new Object(); //listening to the WSconn
wsListener.result = function(evt:Object):Boolean {
trace("in listener");
var toReturn = evt.target.results;
trace(toReturn); //it works, says true or false, can't get it to calling function
return toReturn; //where in hell does this go?
};

wsListener.status = function(evt:Object) {
switch (evt.code) {
case 'Fault' :
trace("ERROR! ["+evt.data.faultcode+"]");
trace(" "+evt.data.faultstring);
break;
case 'InvalidParams' :
trace("ERROR! ["+evt.code+"]");
break;
}
};

everything works (valid codes are returned from the Db as "true", as shown in the second trace. any help w/b appreciated. FlashMXP2004

Assign Function With Parameters To Listener.onSomething
Hi all,
I have written a class with some methods. Furthermore I am using a listener which should call a method of the class.
As long as the called method dont need parameters everything is fine ...


Code:
keyInput.onKeyDown = myFunction;
But ... in this case the myFunction() of my class should be called with some parameters assigned. The solution which works for me is looking like that ...


Code:
keyInput._parent = this;
keyInput.onKeyDown = function() {this._parent. myFunction(param)};


Is there a smarter way to get this thing workin?

thx in advance
ckey

Can I Have An Event Listener For A Movieclip's StartDrag Function?
hey. lets say i have a movieclip of a beach ball, and i have it startDrag() on mousedown like so:

beachball.addEventListener(MouseEvent.MOUSE_DOWN, moveBall);
function moveBall(event:Event):void {
beachball.startDrag();
}

i want it so while the beachball is being dragged around, it trace()'s the ball's X and Y coordinates out. how do i make an event listener for when the beachball is under a startDrag() status?

Copyright © 2005-08 www.BigResource.com, All rights reserved