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




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



Ultrashock Forums > Flash > ActionScript
Posted on: 2008-10-01


View Complete Forum Thread with Replies

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

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

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

Dynamic Function On Event Handler
Hi, i am creating a simple menu and all of my data is stored in a struct that was pulled over from a text file using loadVars.

This is supposed to populate the menu

Code:
function populateMenu(articleStruct)
{
var i = 1;
//while(i < articleStruct.num)
while(i < 8)
{
_root.attachMovie("btnArticle","btnArticle"+i,i);
_root["btnArticle"+i].menuText.text = articleStruct["artitle"+i];
_root["btnArticle"+i]._x = 65;
_root["btnArticle"+i]._y = 100+i*20;

var curDate = articleStruct["date"+i];
var curTitle = articleStruct["artitle"+i];
var curArticle = articleStruct["article"+i];
_root["btnArticle"+i].onRollOver = function()
{
_root.articleTextVar = curArticle;
_root.titleTextVar = curTitle;
_root.dateTextVar = curDate;
trace("I: " + i);
}
i++;
}
}
It creates the buttons fine, but when it comes to the functions attached i am stuck. It always uses the same article no matter what button i rollover. So i added it to trace the i, and it is revealing the last i set in the while loop. Is there really only one instance of this function and it keeps writing itself over?

Thanks

Function & Dynamic Event Handler Not Working
it looks fine to me but it's not working. i have been doing actionscript for awile now.

Code:
_root.ship.onEnterFrame = function() {
//below not working
trace("HI");
}

Right Clicking Listener Or Event Handler
i want to use the right click on the mouse and pause the video when the user right clicks does any know how to do this i called macromedia/adobe and they sid it was reserved for the context menu and did not have an event handler for right clicking does any one have a fix for that?

Event Listener Replacing Change Handler
Has anybody successfully migrated .fla files from Flash MX to Flash MX 2004 with ActionScript 2?

Specifically, I have a combo box which works in Flash MX (published for Flash Player 6) but not in MX 2004 Pro (published for Flash Player 7).

I can't figure out how to replace my old setChangeHandler code with the new EventListener code. Here's the code that works fine if published for Flash Player 6:

<snip>
combo.setChangeHandler("selectCombo");
function selectCombo(component) {
if (component.getSelectedItem().label == "Saturday") {
_parent.gotoAndStop(10);
} else {
setProperty("alert", _visible, true);
}
}
</snip>

This code lives in the first frame of the associated timeline.
Has anybody re-written code for a combo box that simply waits for a user to make a selection and then acts on that selection?

Listener Objects Vs Event Handler Functions ...
If this is an example of the listener object approach:

Code:
myObj = new Object();
myObj.onMouseDown = myFunction;
function myFunction() {
trace("tracing something");
}
Mouse.addListener(myObj);
... and the listener object approach is favored over the event handler function approach, what would the above code look like if it were written with the event handler function approach.

Where you can use one approach, can you always use the other ? (trying to understand the difference and where to use one instead of the other).

Apparently, the main reason the listener object approach is favored is because multiple listener objects can receive events from the same component/movieclip/etc. Does anyone have an example of this so I can see the advantage in action.

Thanks in advance for any assist.

Listener Objects Vs Event Handler Functions ...
If this is an example of the listener object approach:

Code:
myObj = new Object();
myObj.onMouseDown = myFunction;
function myFunction() {
trace("tracing something");
}
Mouse.addListener(myObj);
... and the listener object approach is favored over the event handler function approach, what would the above code look like if it were written with the event handler function approach.

Where you can use one approach, can you always use the other ? (trying to understand the difference and where to use one instead of the other).

Apparently, the main reason the listener object approach is favored is because multiple listener objects can receive events from the same component/movieclip/etc. Does anyone have an example of this so I can see the advantage in action.

Thanks in advance for any assist.

Listener Objects Vs Event Handler Functions ...
If this is an example of the listener object approach:

Code:
myObj = new Object();
myObj.onMouseDown = myFunction;
function myFunction() {
trace("tracing something");
}
Mouse.addListener(myObj);
... and the listener object approach is favored over the event handler function approach, what would the above code look like if it were written with the event handler function approach.

Where you can use one approach, can you always use the other ? (trying to understand the difference and where to use one instead of the other).

Apparently, the main reason the listener object approach is favored is because multiple listener objects can receive events from the same component/movieclip/etc. Does anyone have an example of this so I can see the advantage in action.

Thanks in advance for any assist.

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.

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;
        }

    }


Get Name Of Function / Event Handler
Does anyone know if there is a way to get the name of the function that my code is running inside?

Code:
_btn.onPress = function () {
trace(something);
}
this would then output "onPress" or something like it... hope you all understand what i'm searching for.

Thanks!

Function Variables Within A Change Handler
Is there anyway to call a function in a change handler WITH the normal function syntax? What I mean is, can I call function myFunction like so:

myFunction(x, y);

Thanks for any help!

Flexible Event Handler Function
Is there a way to create a function that handle events (especially MouseEvents) and still call this function as a plain one without passing any arguments? All this time, I just create an extra function that handles the mouseEvent and call the needed function inside it.

Example:

function handler(e:MouseEvent):void{
realFunction();
}

function realFunction():void{
// I want this function to work as a handler and at the same time a plain function
}

Just thought that maybe there's a better way of doing it.

Thanks in advance.

[F8] Passing Variables To A Named Function Handler
Hiya,

struggling to find an answer to this one, possibly because I can't think of the correct words to describe the query (see the thread title!). A quick heads up would be wonderful.

I'm setting up an onRelease handler for a button, and want it to use a named function rather than an anonymous one. Simple. However how do I pass a variable/parameter to that function?

button.onRelease = buttonHandler(theVar);

just runs the function at the time the above assignment happens, obviously. How do I pass the variable through when it's responding to the event?

I'm going to have a lot of handlers doing something similar, just with different strings. I'm sure I could get at the string I want another way, but I'd really like to be able to do this, since I've come across it a few times.

Cheers,
Si

Function Only Works At Runtime, Not Event Handler
Hi All;

anyone can help me figure out why this only works when my function buttonCount(); is called a runtime? When I call it via the event hander, it doesn't work.

I'm trying to make a dynamic set of sub-menu buttons, determined by the number is var sCount.

Thanks in advance -- code below, .fla attached.
J
-------
var sCount:Number = 4
var dButton:MovieClip;

function sButton() {
for (i = 1; i <= sCount; i++) {
_root.attachMovie("slide", "slide" + i, i);
dButton = _root["slide" + i];
dButton._x = 200 + (27 * i);
dButton._y = 400;
}
}

// --- this works only when the function called at runtime, not via the button - why??? //
sButton();

btn.onRelease = function () {
sCount = 4;
sButton();
}


slide1.onMouseDown = function() {
if (this.hitTest(_root._xmouse, _root._ymouse)) {
trace ("slide 1");
updateAfterEvent();
}
}

slide2.onMouseDown = function() {
if (this.hitTest(_root._xmouse, _root._ymouse)) {
trace ("slide 2");
updateAfterEvent();
}
}

slide3.onMouseDown = function() {
if (this.hitTest(_root._xmouse, _root._ymouse)) {
trace ("slide 3");
updateAfterEvent();
}
}
slide4.onMouseDown = function() {
if (this.hitTest(_root._xmouse, _root._ymouse)) {
trace ("slide 4");
updateAfterEvent();
}
}

How Do I Create A Childs Function And OnEnterFrame Handler
I just dove into AS3 and the differences from AS2 are bigger than I thought they would be.

The thing I’ve been trying to figure out for two hours now is how to create functions and handle the event ENTER_FRAME in an added child (a MovieClip).

In AS2 you could write like this:

this.createEmptyMovieClip("mc1",1);
this.mc1.traceX = function(){
trace(this._x);
}
this.mc1.onEnterFrame = function(){
this.traceX();
}

How do I write this in AS3?

Thanks for helping!

Event Handler Function Returns Values - HOW To Get Them?
Hello I probably am not understanding how Events work....well I have function in a class that has this line of code:


ActionScript Code:
this.addEventListener("dataRetrieved", handleHierSelectData);

"dataTrieved" is a custom event that dispatches an event with a variable set to "true".

In another section of my code I have the event dispatch:


ActionScript Code:
public function onGetRecordsResult(result:Array = null):void
{
    // convert the result array into an array
    phpData = new ArrayCollection(result);
   
    // instantiate new custom event, set the appropriate data to send back and
    // dispatch event to parent app or component
    var e:DataRetrievedEvent = new DataRetrievedEvent();
    e.dataRetrieved          = true;
    dispatchEvent(e);
}

From the addevent listener line I call "handleHierSelectData"


ActionScript Code:
public function handleHierSelectData():Canvas
{
    newProgressBar.indeterminate = false;
    newProgressBar.visible       = false;
   
    newHierSelect = new ThreeLevelHierSelect('processData', listLabels, null, phpData);
    //myCanvas.addChild(newHierSelect.generateHierSelect());
   
    return newHierSelect.generateHierSelect();
}

See, handleHierSelectData creates a new component that I need to send to my main application so I am wonder WHERE, AND HOW I can get the returned component from this.addEventListener("dataRetrieved", handleHierSelectData); ??

I am missing something here?

I guess what I want to know is...when you have an event listener and you want the handler function to return something HOW do you catch it and where?

Stop Function Created In OnClipEvent Handler
How do you do what is in the topic? LEt's say that function is on a MC, and then you are a few MCs away and a few parents up. How do you refer to it. You use the delete action, right? I just can't picture how I would do it. For _root.onEnterFrame and within the same frame or same MC, you just use
"delete _root.onEnterFrame", right? But how about when it's in an onClipEvent (enterFrame).
Do I just use something like this to stop one and start another:

ActionScript Code:
onClipEvent (enterFrame) {if (_root.gsSolved) {delete _parent_parent.myMovieClip.growGreenScale();shrinkGreenScale();}}

How To Call Function On Class Event Handler
Hi friends..i have simple question about how to call a function on a class but i dont know how to do it, would you mind to help me,please.
I have a class :


Code:

class MyClass{
private var lvSendState:LoadVars;
private var lvLoadState:LoadVars;

public function Test(){
trace("function Test Run");
}

public function LoadSomeThing():Void{
lvSend=new LoadVars();
lvLoad=new LoadVars();
lvSend.sendAndLoad("some url", lvLoad);
lvLoad.onLoad = function(){
//try to call function Test
Test(); //This is doesn't work
}
}
}
I try to call function Test on lvLoad.onload but i doesn't work,does any body tell me how to call it ? thanks in advance

Stop Function Created In OnClipEvent Handler
How do you do what is in the topic? LEt's say that function is on a MC, and then you are a few MCs away and a few parents up. How do you refer to it. You use the delete action, right? I just can't picture how I would do it. For _root.onEnterFrame and within the same frame or same MC, you just use
"delete _root.onEnterFrame", right? But how about when it's in an onClipEvent (enterFrame).
Do I just use something like this to stop one and start another:

ActionScript Code:
onClipEvent (enterFrame) {if (_root.gsSolved) {delete _parent_parent.myMovieClip.growGreenScale();shrinkGreenScale();}}

Does SetSelectedIndex In Combobox Call The Change Handler Function
does the function setSelectedIndex for combobox object call the change handler function? It seems that sometime it will call it and sometime it will not, am I the only one with this phenomenon?

Access A Super Class Function From Event Handler
Here is my Sub Class extending superClass. I just want to access a method of my superClass "createBG(width:String,height:String)" inside my subClass method "setXML()" but under the event Handler "xml.onload"
Please give me some suggestions about syntax or logic anything.



Class subClass extends superClass{

function subClass(){

trace("SubClass")

}


function setXml(){
var myxml:XML = new XML();
var mmX=myxml.load(url);
myxml.ignoreWhite=true;
myxml.onLoad=function(success){

// Here I want to access the super class method createBG(width:String,height:String);

//super.createBg(400,500); I have tried this. but no output.

}

}


}

Buttons Inside MC Not Working When Event Handler Function Is Assigned To MC
Please help!

I have a button on the stage that I assigned an event handler method to:

button1_bt.onRollover = function(){
animation1_mc.gotoAndPlay(10);

This is perfect. It plays the animation which is a drop down menu then stops in the dropped down state. However, I want "animation1_mc" to play it's pull up animation, starting on frame 21, when the MC is rolled off of. So I added this event handler method:

animation1_mc.onRollOut = function(){
animation1_mc.gotoAndPlay(21);
}

This also works, EXCEPT, the buttons inside the MC "animation1_mc" do not work! How can I have the pull up animation play on rollout o th e MC without disabling the buttons inside the MC???!!!

Passing Values, AddEventListener, MouseEvent Handler Function Help Request
Hello,

I have pasted the current code below. I wish to have a group of images enlarge and shrink as the mouse passes over them (eventually smoothly, not jerky as they are now, as well as fading from B&W to color on enlargement - but not relevant to this question).

As you can see I have written a separate Grow and Shrink function for each image, but this is very inefficient (I am an old hand at VBScript, but new to Actionscript).

I am seeking a way to pass the instance in question to the function so I can use one grow and one shrink function for any/all of the images that will be used, such as (where "1" is the item passed and "whichItem" represents what I am trying to do here):

galleryLoader1.addEventListener(MouseEvent.MOUSE_OVER, growImage(1));
galleryLoader1.addEventListener(MouseEvent.MOUSE_OUT, shrinkImage(1));

function growImage(event:MouseEvent, whichItem):void {
whichItem.x = whichItem.x - (whichItem.width / 2);
whichItem.y = whichItem.y - (whichItem.height / 2);
whichItem.scaleX = 1;
whichItem.scaleY = 1;
}


...... etc.

When I attempt to pass data at the addEventListener line in the line:

galleryLoader1.addEventListener(MouseEvent.MOUSE_OVER, growImage(1));

I always get errors that tell me I am trying to coerce the mouseevent to a string, and the wrong number of arguments (expecting 2). If I put two arguments in, I get a boatload of errors.

I am new, confused, but thoroughly impressed with Actionscript 3.0. I have only been working with it for about a week now and can do a lot, but this particular thing has me stumped.

THANK YOU for any assistance you can render so I can get this function running. The information is probably in several places, but I do not yet know enough to be able to know where or how to look to get my answer. Your help is of tremendous value and is appreciated.

Best regards,

Dave Xanatos


Code extracts (less the imports, addChilds, Loaders and URLRequests...):

galleryLoader1.addEventListener(MouseEvent.MOUSE_OVER, growImage1);
galleryLoader1.addEventListener(MouseEvent.MOUSE_OUT, shrinkImage1);
galleryLoader2.addEventListener(MouseEvent.MOUSE_OVER, growImage2);
galleryLoader2.addEventListener(MouseEvent.MOUSE_OUT, shrinkImage2);
galleryLoader3.addEventListener(MouseEvent.MOUSE_OVER, growImage3);
galleryLoader3.addEventListener(MouseEvent.MOUSE_OUT, shrinkImage3);
galleryLoader4.addEventListener(MouseEvent.MOUSE_OVER, growImage4);
galleryLoader4.addEventListener(MouseEvent.MOUSE_OUT, shrinkImage4);


function growImage1(event:MouseEvent):void {
galleryLoader1.x = galleryLoader1.x - (galleryLoader1.width / 2);
galleryLoader1.y = galleryLoader1.y - (galleryLoader1.height / 2);
galleryLoader1.scaleX = 1;
galleryLoader1.scaleY = 1;
}

function growImage2(event:MouseEvent):void {
galleryLoader2.x = galleryLoader2.x - (galleryLoader2.width / 2);
galleryLoader2.y = galleryLoader2.y - (galleryLoader2.height / 2);
galleryLoader2.scaleX = 1;
galleryLoader2.scaleY = 1;
}

function growImage3(event:MouseEvent):void {
galleryLoader3.x = galleryLoader3.x - (galleryLoader3.width / 2);
galleryLoader3.y = galleryLoader3.y - (galleryLoader3.height / 2);
galleryLoader3.scaleX = 1;
galleryLoader3.scaleY = 1;
}

function growImage4(event:MouseEvent):void {
galleryLoader4.x = galleryLoader4.x - (galleryLoader4.width / 2);
galleryLoader4.y = galleryLoader4.y - (galleryLoader4.height / 2);
galleryLoader4.scaleX = 1;
galleryLoader4.scaleY = 1;
}

function shrinkImage1(event:MouseEvent):void {
galleryLoader1.x = 130;
galleryLoader1.y = 350;
galleryLoader1.scaleX = .5;
galleryLoader1.scaleY = .5;
}

function shrinkImage2(event:MouseEvent):void {
galleryLoader2.x = 330;
galleryLoader2.y = 350;
galleryLoader2.scaleX = .5;
galleryLoader2.scaleY = .5;
}

function shrinkImage3(event:MouseEvent):void {
galleryLoader3.x = 560;
galleryLoader3.y = 350;
galleryLoader3.scaleX = .5;
galleryLoader3.scaleY = .5;
}

function shrinkImage4(event:MouseEvent):void {
galleryLoader4.x = 730;
galleryLoader4.y = 350;
galleryLoader4.scaleX = .5;
galleryLoader4.scaleY = .5;
}

Designer Tries Code - Needs Basic Help (a Multiple Button Event Handler Function)
I know this is most inelegant and I'm wondering if there is an easy way to clean this up rather than repeating it 12 times. These are invisible buttons controlling movieclips underneath.

How would I write a function that would take care of all of them, given that the instance names of each object contains the same numeral within each set of methods?

(A fair number of eyes roll skyward about now - I'm a newb)


// button event handler methods
//------------
if (b1_mc._currentframe<4) {
b1_btn.onRelease = function() {
_root.gotoAndPlay("s1");
};
b1_btn.onPress = function() {
b1_mc.gotoAndStop(3);
};
b1_btn.onRollOut = function() {
b1_mc.gotoAndStop(1);
};
b1_btn.onRollOver = function() {
b1_mc.gotoAndStop(2);
};
}
//------------
if (b2_mc._currentframe<4) {
b2_btn.onRelease = function() {
_root.gotoAndPlay("s2");
};
b2_btn.onPress = function() {
b2_mc.gotoAndStop(3);
};
b2_btn.onRollOut = function() {
b2_mc.gotoAndStop(1);
};
b2_btn.onRollOver = function() {
b2_mc.gotoAndStop(2);
};
}
//------------
if (b3_mc._currentframe<4) {
b3_btn.onRelease = function() {
_root.gotoAndPlay("s3");
};
b3_btn.onPress = function() {
b3_mc.gotoAndStop(3);
};
b3_btn.onRollOut = function() {
b3_mc.gotoAndStop(1);
};
b3_btn.onRollOver = function() {
b3_mc.gotoAndStop(2);
};
}
//------------
if (b4_mc._currentframe<4) {
b4_btn.onRelease = function() {
_root.gotoAndPlay("s4");
};
b4_btn.onPress = function() {
b4_mc.gotoAndStop(3);
};
b4_btn.onRollOut = function() {
b4_mc.gotoAndStop(1);
};
b4_btn.onRollOver = function() {
b4_mc.gotoAndStop(2);
};
}
//------------ etc....

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.

Dynamic Event Handler Help
So I found this really great snow effect, but its coded for flash 5.

Because of the onClipEvent (enterFrame) code, I can't make it stop after 15 seconds. Well, I don't know HOW to make it stop after 15 seconds. does anyone? if not, can someone help me throw this code into a function so that I can apply a getTimer(); to it and stop it after 15 seconds?

Heres the code:


onClipEvent (load) {
//variables
width = 305;
height = 250;
//random x,y, and alpha
this._xscale = this._yscale=50+Math.random()*100;
this._alpha = 20+Math.random()*50;
//random x and y for flakes
this._x = -width+Math.random()*(3*width);
this._y = -10+Math.random()*height;
//speed and trigonometric value
i = 1+Math.random()*2;
k = -Math.PI+Math.random()*Math.PI;
rad = 0;
}
onClipEvent (enterFrame) {
// horizontal movement
rad += (k/180)*Math.PI;
xmovement = _root._xmouse;
this._x -= Math.cos(rad)+(xmovement-(width/2))/50;
// vertical movement
this._y += i;
// remove clips when they misbehave (overstep boundaries)
if (this._x>(width+50)) {
this._x = -45;
this._y = Math.random()*height*2;
}
if (this._x<-50) {
this._x = width+45;
this._y = Math.random()*height*2;
}
if (this._y>=height) {
this._y = -50;
this._x = -width+Math.random()*(3*width);
}
}

Help On Dynamic Event Handler
Hi thr!

This is what I have:

1 movieclip with the following script on it:

onClipEvent (load) {
divalpha = 5;
_alpha = 0
}
onClipEvent (enterFrame) {

if (this._parent.barra_nav1._x <=350) {
_alpha += (endalpha-_alpha)/divalpha;
endalpha = 100
}

}

Which means that my mc wait till other movie (barra) reaches a certain point and then fades in.

What I need to accomplish:

I need that after this "marvelous" fading in, if the user rollover the mc it fades back to 20% alpha using the same formula and fades back to 100% when the user rollout.

As I´ve declared in the enterFrame that the alpha is equal to 100% I´m not getting the results I need.

Ive been searching for tutorials on Dynamic Event handlers with no results but I'm sure there most be a way to overwrite the first enterFrame...

HELP PLEASE!!!!!!!

Thx in advance

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?

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?

[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);
...
});

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!

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

Dynamic OnClipEvent Handler Problem
If I remove:

Code:
_root["barrier"+i].onEnterFrame = function() {
I get the exact same effect. Why is the code above doing nothing instead of changing newly duplicated object’s onEnterFrame handlers?


Code:
onClipEvent (load) {
var i = 1;
var speed = 10;
Stage_height = Stage.height;
this._x = random(550);
this._y = random(550)*-1;
}
onClipEvent (enterFrame) {
if (Key.isDown(Key.SPACE)) {
i++;
duplicateMovieClip(_root.startbarrier, "barrier"+i, i);
//The code below in bold is what new object's On enterFrame code should be.
//The line of code below seems to do nothing.
_root["barrier"+i].onEnterFrame = function() {
if (this.hitTest(_root.trailmaker)) {
trace("Player Died");
}
if (this._y>Stage_height) {
this.removeMovieClip();
}
this._y += speed;};
}
}
Any help at all would be extremely appreciated.

Dynamic Loop Event Handler
Hello, I have a loop which dynamically generates the name of 3 textFields: philsText1, philsText2 and philsText3.
How can I also dynamically create 3 different function names in this code:

this["philText"+i].addEventListener(MouseEvent.MOUSE_DOWN, mousedown1);

eg. I want to generate mousedown1, mousedown2 and mousedown3 dynamically.
Is there any way ?

Thanks for any help.

Dynamic Event Handler Problem?
HEllo-

I am creating a photo gallery... I load all the thumbnail images dynamically into an empty movieClip which is attached to a movie clip called "thumbs" from the library. all is working, except the onRelease method for each thumbnail mc is not triggering. here is the code- thanks for your wisdom!

//loadThumbs();
for (i = 1; i < 17; i++) {
var t = "thumb" + i;
thumbs.attachMovie("image", t, i);
thumbs[t]._x = 85*(i-1);
thumbs[t].loadMovie(this.pathToThumbs + this.tArray[i], i);
thumbs[t].onRelease = function() {
thumbnail(this);
trace(this);
};
}

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

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