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




Delete Delegate...



Hello there...

Ok a question regarding the delegate class...

i'm using it to delegate the onEnterFrame event of my root to the engine function of my game class (the each frame the player will move, collision and so on)

The thing is I want to stop the engine running at a certain time (eg game over)
But I don't know how to stop it.
i tried to delete the onEnterFrame event of the root or make it null. no success

Now I'm using AsBroadcaster to achive it...

But my curiosity make me ask that

Thx for any answer

C ya guys/gals



ActionScript.org Forums > ActionScript Forums Group > ActionScript 2.0
Posted on: 12-16-2005, 03:06 AM


View Complete Forum Thread with Replies

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

How To Delete Movieclip From Delete Key And Backsp
how to delete textfield movieclip from delete key and backspace

AS 2 Delegate
Hi, a question.
I'm talking about AS 2.

In a class I've:

btnCollection.onRollOver = function() {
// this._name is a button name
var t = Number(this._name.substr(1, 1));
//
Mouse.hide();
// cRef is a reference to the class
cRef.cursor._visible = true;
startDrag(cRef.cursor, true);
//
cRef.setRotation(cRef.curPos[t]);
};

btnCollection is previously created, this way:

for (i=0; i<btns; i++) {
var btnCollection = targetLevel['c'+i+'_btn'];
}

cRef is previously created this way:
var cRef = this; // it stores a reference to the class.

the var t registers a number contained in a button name (I use that
number to perform various tasks).

This is perfectly working, but now I want to use the Delegate class.

So, I did the following:

btnCollection.onRollOver = Delegate.create(this,
btnRollOver(btnCollection));

after having built this method:

private function btnRollOver(whichBtn) {
var t = Number(whichBtn._name.substr(1, 1));
//
Mouse.hide();
//
cursor._visible = true;
startDrag(cursor, true);
//
setRotation(curPos[t]);
}

nothing works like before.

That is: I probably easily get the class reference but I've lost the
reference to the single button...

Please, can you help me better understand (and solve) this issue?

Thanks!

Better Delegate Class
Hey everyone,

I got myself into a situation where I need Delegate.create to take in more than two arguments, much like setInterval.

For example:

Code:
mc.onRelease = Delegate.create(this, thumbOnRelease, mc);

function thumbOnRelease(mc:MovieClip):Void
{
trace("mc: " + mc);
var pic:Picture = mc.pic;
_classLargePicMgr.loadPic(pic);
}


I want to be able to pass on mc. I had to use Delegate because I needed to access a private variable (_classLargePicMgr) in the class which all the code is in.

Is there a solution to this? Or will I have to create my own "Delegate class"?

Using Mx.util.Delegate
I am updating my flash knowledge and teaching myself Flash 8 and trying to make this example work:

Code Block 1


Code:
import mx.util.Delegate
this.onXMLLoad = function() {
trace(this);
}
var xml:XML = new XML();
xml.onLoad = Delegate.create(this, onXMLLoad);
xml.load("http://www.dannypatterson.com/XML/rss.xml");

Code Block 2


Code:
this.onXMLLoad = function() {
trace(this);
}
var xml:XML = new XML();
xml.onLoad = onXMLLoad;
xml.load("http://www.dannypatterson.com/XML/rss.xml");
When I execute Code Block 2 I get the XML once it is loaded because this refers to the xml object.

However, when I execute code block one, I get nothing... No instance name, no trace screen. Why I am expecting to get a reference to the root or something correct. What is the deal with this Delegate Mess?

The Delegate Class
Hi all,

the Delegate class is not fully supported in mx2004. also i have a paoblem about it.

ActionScript Code:
import mx.utils.Delegate;
class Action {
    private var rootLevel:MovieClip;
    private var _clip:MovieClip;
    function Action(myRoot:MovieClip) {
        rootLevel = myRoot;
        fCreate();
    }
    public function get clip():MovieClip {
        return _clip;
    }
    public function set clip(mClip:MovieClip):Void {
        _clip = mClip;
    }
    private function fCreate() {
        var refMc:MovieClip = rootLevel.createEmptyMovieClip("myMc_1", rootLevel.getNextHighestDepth());
        refMc.beginFill(0x0000FF, 30);
        refMc.lineStyle(1, 0x000000, 100);
        //trace(refMc);
        refMc.moveTo(10, 10);
        refMc.lineTo(110, 10);
        refMc.lineTo(110, 110);
        refMc.lineTo(10, 10);
        refMc.endFill();
        [color="Blue"]refMc.onPress = Delegate.create(refMc, refMcOnPress(refMc));
        refMc.onRelease = Delegate.create(refMc, refMcOnRelease(refMc));
        //trace(this);
    }
    private function refMcOnPress(obj:MovieClip) {
        trace("onPress "+obj);
    }
    private function refMcOnRelease(obj:MovieClip) {
        trace("onRelease "+obj);
    }[/color]   }

an dinamically created button object and its onPress, onRelease events was directed to a function with Delegate class. BUT it's not working. need help.

RemoveEventListener And Delegate
I can get events from an event dispatcher by

Code:
mouth.addEventListener ("finishedTalking",Delegate.create(this, this.shutUp))
and this.shutUp gets called nicely when mouth has finished talking.
In my sitaution mouth conitues to fire off finishedTalking events but I want ot ignore them so

Code:
private function shutUp()
{
mouth.removeEventListener ("finishedTalking", ?????);
}
The ????? bit here is the tricky bit. It should be a reference to the listener, but what is my listener?
I've tried this, this.shutUp and Delegate.create(this, this.shutUp) and I can't stop the events coming.
There are work arounds but this sort of issue is in a lot of places in the code I'm working on so I want a proper fix.

Using A Delegate With OnLoadInit
Hello,

This is probably an easy one, but has me stumped right now. I'd like to use a delegate for my onLoadInit function, but still have access to the target_mc variable that is usually accessible to the onLoadInit function. How would I do this?

Thanks,
cnatale

Delegate Class
What exactly is the delegate class? I understand that you would want to use this for dealing with scope issues, however I have no clue where to begin as to researching what it can do and how it can help.

Delegate Class
why is it better to use the delegate class instead of an inline function?

myButton_mc.onRelease = function(){....}

myButton_mc.onRelease = Delegate.create(this,"doSomething");

they both do the same thing dont they?

thank you

Why Do I Delegate When I Can Apply?
What is the advantage of using a Delegate class in as2? I realize that it's old news for as3 guys. But Ive got a medium sized as2 project and Im going through my code and wondering why Im using Delegate.create sometimes. What's wrong with "apply"?

I admit that I must have jumped on the Delegate bandwagon without thinking anything more than "dhuu...thats what the pros must be using".

Am I right in saying that there is nothing at all wrong with simply saying "function_name.apply( this, args )"? Or am I missing something? Is it a matter of memory management? I've done a lot of research on delegation and read all kinds of blogs and scripts from little tweeks to the official.. to >200 lines. Yikes! At the end of the day I wrote my own little delegate class that worked for me (just a rewrite of Proxy without loops). But now that I go though my code I see that I might as well have just used apply because that's all Im doing with it!

Id like to be a better programmer. What am I missing and why shouldn't I do a find and replace here. Why is it better to wrap up "apply"? Will I be better readied to learn other languages? If thats it Im all for it. Could you tell me why?

I just don't understand why I was so convinced that I needed the delegate class when I had "apply" out of the box.

Thanks and I hope I didnt take up too much space here.

Using The Delegate Class
Hi there,
I'm having trouble using the delegate.create method (my first time using it!). Here's part of a class I have...


Code:
public function SiteData(xmlFile:String) {
imagesXML = new XML();
imagesXML.ignoreWhite = true;
imagesXML.onLoad = function(ok) {
var pictureURLS:Array = new Array();
if (ok) {
var myArray:Array = this.firstChild.childNodes;
for (var i:Number = 0; i < myArray.length; i++) {
pictureURLS.push(myArray[i].childNodes[0].childNodes[0]);
pictureCaptions.push(myArray[i].childNodes[1].childNodes[0]);
}

if (!_root.builtStack) {
_root.builtStack = true;
Delegate.create(this, buildStack);
}
}
};

imagesXML.load("testGallery.xml");
}

public function buildStack() {
trace("IN BUILDSTACK");
}
But the Delegate.create line isn't calling buildStack (and tracing out "IN BUILDSTACK"). Is it something to do with the Delegate.create declaration being in an XML's onLoad??

Any help would be great.

Many thanks,
Dave

Delegate With Delay? Possible?
Hi Guys, I'm trying to figure out how to create a delegate, but with an added delay, so that when I call a method on an object it not only delgates, but also adds a delay in milliseconds...

The problem is that i'm not too familar with the inner workings of the Delegate.create method, so any ideas or explanations or very welome!

Does something like this already exist?

Thanks
Ryan

OOP Troubles: Delegate With Iteration
Hi there.

I'm using iteration within a class method to attach a series of button instances from the library to mc in my fla. So far so good, but when I try to use Delegate to give them an onRelease handler, it only works on the last button. Here is the rellevent code:


Code:
//CREATE BUTTONS FROM XML
public function attachButtons (buttonLabel:Array, totalButtons:Number, buttons:Number):Void {

//SET ITEM VARS
numVisibleItems = buttons;
numOfItems = totalButtons;

var thisLb:XmlListBox = this;
var i;

//ITTERATE THROUGH ARRAY TO PLACE BUTTONS
for (i = 0; i < numOfItems; i++) {
buttonContainer_mc = listBoxContainer_mc.background_mc.attachMovie ("listBoxButton", "button" + i, listBoxContainer_mc.background_mc.getNextHighestDepth ());
buttonContainer_mc._y = buttonContainer_mc._height * i;
buttonContainer_mc.title_txt.text = [i + 1] + " " + buttonLabel[i];
buttonContainer_mc.onRelease = buttonContainer_mc.onReleaseOutside = Delegate.create(this, setButtons, i);

buttonContainer_mc.thisSelected_mc._alpha = 0;

}

sizeMask ();
}

function setButtons(i:Number):Void {

buttonContainer_mc._alpha = 100;
trace("IDENT"+buttonContainer_mc.thisSelected_mc._alpha);
trace("I IS:"+ i);
//current_track_number = i;
//stopmusic();
//playmusic();

}


Thanks a lot.

[F8] Delegate Scope Issue
Code:
import flash.display.BitmapData;
import mx.utils.Delegate;
class Load extends MovieClip {
private var which:String;
private var _delegate:Function;
private var myBitmap:BitmapData;
function Load(which) {
_delegate = Delegate.create(this, fDo);
myBitmap = BitmapData.loadBitmap(which);
_delegate(which);
}
private function fDo(which) {
trace(this._parent);
_parent.createEmptyMovieClip("mc", this.getNextHighestDepth());
_root.attachBitmap(myBitmap, this.getNextHighestDepth());
}
}
because i called fDo using delegate I thought that using _parent would work. It doesnt though.
What am I doing wrong, It works using _root but I dont really want to.
Thanks

LoadVars, SendAndLoad + Delegate = ?
Hello, I am having a few problems with loadVars and Onload.

The onload gets called fine, but it's not pulling in the variable from the asp page.

ASP CODE--
response.Write("&userInfo =false")

Flash Code --

Code:
public function login() {
trace("login");
var login_lv = new LoadVars();

login_lv.onLoad = Delegate.create(this, function (userInfo:Object) {
trace(userInfo);
});


_global.username = formParent.f_name.text;
login_lv.username = formParent.f_name.text;
login_lv.password = formParent.f_password.text;
login_lv.sendAndLoad(_global.serverURL+"login.asp",login_lv,"POST");
}


FLASH CODE THAT WORKS---


Code:
public function login() {
trace("login");
var login_lv = new LoadVars();

login_lv.onLoad = function() {
if (this.userInfo == "true") {
trace("Access Granted");
trace("_global.username "+_global.username);
} else {
_global.username = null;
trace("Access Denied");
createNotice("* Username allready exsist. Please choose another one.");
}
};
_global.username = formParent.f_name.text;
login_lv.username = formParent.f_name.text;
login_lv.password = formParent.f_password.text;
login_lv.sendAndLoad(_global.serverURL+"login.asp",login_lv,"POST");
}
I need to get the delegate way working as I need to be in the correct scope for what I want to do next.

Any idea where I am going wrong.

Many thanks

Kaan

XML Extension + Scope / Delegate
Hi all I wrote to following a long time ago and use it often but it's a pain:


Code:
class com.BMace.BJMXML extends XML
{

function BJMXML ( Void )
{
//
}
public function SendNodes (SearchName:String, TheNode:XML, Callback:Function, Scope:Object)
{
for(var i:Number = 0; i < TheNode.childNodes.length; i++)
{
var CurrentNode = TheNode.childNodes[i];
if(CurrentNode.nodeName != null)
{
if(CurrentNode.nodeName == SearchName)
{
Callback(CurrentNode, Scope);
}
if(CurrentNode.childNodes.length > 0)
{
SendNodes(SearchName, CurrentNode, Callback, Scope);
}
}
}
}
}


Basically you can declare a BJMXML object and search for a node like so:


Code:
SomeBJMXMLObject.SendNodes("someNodeName", SomeXML, FunctioToCall, TheCurrentScope);


I have to pass in the scope for the returned cal else I can access anything in the base class. Does anyone have an idea how to go around this with delegate or some other manner? I't a reall neat little function but I feel like I'm making things harder for myself when I use it.

Delegate Class Problem
I'm using the delegate class to allow my class variables to be referenced inside an xml.onLoad event. More specifically I'm calling a push on an array(which is a member of my class) in the onLoad event function. When I trace the array's length inside the event handler, it does indeed increase incrementally for each object pushed but when I try to trace outside the onLoad event handler it always outputs 0 as if I added nothing. Does anybody know why? I know I use the delegate class to fix the scope problem of the member array in the xml event but do I need to do something else to get the scope of the array back to the class? Or is something else going on?

Delegate A Function To Another Location
ok guys I've a function in a class file I need to be located on the maintimeline of a movie,

I was trying to do sometihng like this:

l_module.getStatus = Delegate.create(this, function ():Status
{
return currentStatus;
});

so inside l_module (which is a movieClip) I would like to call getStatus() but it can't find it.

Is this right? Can it be done? F8 by the way!

Mx.utils.Delegate Demystified
After newblack, I thought it might be a good idea to completely explain away the Delegate class. To understand how it works, you will need an understanding of how a function executes in a particular scope, or "context", which is explained in this thread.

In AS, each function is an object of type Function. The Function class has a method apply(scope, arguments) defined, which, when called, executes the function in the given scope with the given arguments. Now we have everything we need to understand the code of the mx.utils.Delegate class, which, luckily, is only a few lines long. There is little in that class besides its main workhorse, the create() method:


ActionScript Code:
/**
    Creates a functions wrapper for the original function so that it runs
    in the provided context.
    @parameter obj Context in which to run the function.
    @paramater func Function to run.
    */
    static function create(obj:Object, func:Function):Function
    {
        var f = function()
        {
            var target = arguments.callee.target;
            var func = arguments.callee.func;

            return func.apply(target, arguments);
        };

        f.target = obj;
        f.func = func;

        return f;
    }

The create() method takes two arguments - the scope in which the function will be executed, and the function to execute it in. create() returns a reference to another function, which is a "wrapper" of the original one. Both the original function and the scope in which it will be executed are stored in the new "delegated" function. When the "delegate" is called, it simply executes the original function in the desired scope. There is no magic. The only complication in understanding might arise from the arguments.callee trick used above so that no memory is wasted on storing the activation object of the "delegate" function (read about activation objects in tim groleau's scope chain article). arguments.callee inside of a function refers to the Function object itself for that function. In the mx.utils.Delegate.create() code above it is used to access the original function and scope, which are stored directly in the "delegate" function Function object. The simplification below would work just as well, but might not be as optimal in terms of memory management:


ActionScript Code:
static function create(obj:Object, origFunc:Function):Function
    {
        var scope:Object = obj;
        var func:Function = origFunc;
       
        var f = function()
        {
            return func.apply(scope, arguments);
        };

        return f;
    }

arguments, in a function, refers to an Array of all the arguments passed to that function. In case of the "delegated" function above, it simply "passes through" all the arguments that were given it to the original function, which is executed in the intended scope.

Now, a question that might arise is: if we call Delegate.create() second time on a function that has already passed through one Delegate.create() call, will it execute in the scope passed to the first Delegate.create() call or the second? If you answered "the first" then you are correct. Delegate.create() permanently attaches an execution scope to the original function, it can not be changed at a later time. If you look at the code, it will become obvious - the original function can only execute in one scope, and that scope is the one supplied with the first call to Delegate.create(). All the other scopes end up being ignored. Now, if you would like to create a Delegate in which you can change the scope of execution, this is where the other two tiny methods of mx.utils.Delegate() come into play:


ActionScript Code:
function Delegate(f:Function)
    {
        func = f;
    }

    private var func:Function;

    function createDelegate(obj:Object):Function
    {
        return create(obj, func);
    }

The original create() method above is static, you did not need to create an instance of the Delegate object in order for it to work, you could call it directly as mx.utils.Delegate.create(...) which returned you the new "delegated" function. A multi-scoped delegate requires you to actually create an instance of the Delegate object, passing it the function to be delegated. Note that in this use no delegated function is created at construction time. It is created only when you successively call createDelegate() on the previously constructed Delegate instance, passing it the scope in which you want the original function to execute. Of course, you could have achieved the same effect with several Delegate.create() calls, passing the same function and different scopes.

Delegate Class Have Function To...
Does the Delegate class have a function that can access a property in a different scope?

Mx.utils.Delegate.create
Hi,
I am using the mx.utils.Delegate.create class to run a function after an event listener is invoked such that:

datareceiver.onLoad = mx.utils.Delegate.create(this,dothis);

The dothis function executes properly, but datareceiver becomes unscopeable in the dothis function. datareceiver is receiving variables back from a php script, so I need access to datareceiver.returnData So, in the dothis function I want to do something like:

this.php_response.text = datareceiver.returnData;

How is this accomplished? and if you could provide a bit of theory behind it that would be great...TIA

Delegate With Multiple Variables?
How can I write a Delegate callback with two functions?

Here is what I have

invBtn1.onRelease = Delegate.create(this, navSubBtnCallbackRelease1);


Here is what I want

invBtn1.onRelease = Delegate.create(this, navSubBtnCallbackRelease, 1);

Can this be done?

SetTimeout And Delegate To Keep Scope
Hi im trying to keep scope in a class with using setTimeout

here is my effort so far which doesnt fire the function
Code:
import mx.utils.*;
class Crackle extends MovieClip {
var val:Number;
var clip:MovieClip;
var setTimeout:Function;
public function Crackle(clip) {
this.clip = clip;
//fAnimate();
}
public function fAnimate() {
trace(this.clip);
Delegate.create(this, _global.setTimeout(fSetAlpha, 1000, 50));
//_global.setTimeout(fSetAlpha, 1000, 50);
//_global.setTimeout(fSetAlpha, 1500, 76);
//_global.setTimeout(fSetAlpha, 500, 40);
//_global.setTimeout(fSetAlpha, 2500, 75);
}
private function fSetAlpha(val) {
trace(">>"+this);
trace("set alpha of "+this.clip+" after "+val+" is value");
clip._alpha = val;
}
}
thanks if you know this one

Using Delegate.create With .txt File,
I am using the following code to read data from a text file "theDummyData.txt".... but i m unable to read the data.... please help.. i need help on this ..
I do not know whether i m using it in correct way. PLEASE HELP!!!

private function loadXML()
{
var myLoadVars:LoadVars = new LoadVars();
myLoadVars.onLoad = mx.utils.Delegate.create(this, receiveXML);
myLoadVars.load("theDummyData.txt");
}

private function receiveXML(success)
{
if (success)
{
//trace(this.graphlabel); // is not working
//trace(this.item1); // is not working
}
}

*******************************************
theDummyData.txt contains the following data
&graphlabel=THIS IS MY LABEL TEST &item1=CAR

Delegate/event Listener Help
I'm looking for help resolving a scoping issue whenever I use the onMotionFinished function of a tween. Is there a way to use delegate to increase the scope of the onMotionFinished function to my entire manager class?

Nifty Trick With Delegate
The hardcore coders here probably already know this trick, but I hadn't ever seen it directly documentated anywhere and figured I'd throw it out there for general consumption. I was frustrated a while back with the inability to pass arguments along to functions directly with Delegate.create. Since the first parameter of Delegate is just an object (any object) in whose scope the function runs, it's possible to do this:


ActionScript Code:
button.onRelease=Delegate.create({scope:this, args:[1,3,true,'a string']}, myFunction);

  function myFunction():Void{
     trace(this.scope) // 'this' from above
     trace(this.args)   //args contains all the variables passed along to the new scope.
  }

Of course, it doesn't have to be an array of args (just like the scope doesn't have to be 'this' if you don't need it to be). It could be anything.

Delegate Class Problem
Hi all...

I'm in a pinch and I'm hoping that someone can help me. I've created a class (with quite a bit of help from the actionscript.org community) and it works beautifully. The purpose of the class is to help me build a graphical interface that shows connections between people and companies in a network. So, I have one person with say 36 connections. My issue is that when I invoke 36 instances of my class, only the last of the 36 instances works. I've included my code below. I know this is a very complex problem, but I'm completely at a loss. Thank you in advance for any help and thank you for your time.

Class code:

Code:
import mx.transitions.Tween;
import mx.transitions.easing.*;
import mx.utils.Delegate;
class connectAgent {
private var parentClip:MovieClip;
private var lineClip:MovieClip;
private var thisDepth:Number;
private var expander:MovieClip;
//constructor
public function connectAgent(clipHome:MovieClip, from:MovieClip, to:MovieClip, lineColor:Number, tox:Number, toy:Number, depth:Number) {
trace(to);
parentClip = clipHome;
from.onRelease = Delegate.create(this, dewIt);
function dewIt() {
trace(to);
if (to._x == tox) {
} else {
new Tween(to, "_x", Regular.easeOut, from._x, tox, .5, true);
new Tween(to, "_y", Regular.easeOut, from._y, toy, .5, true);
}
drawLine(clipHome, from, to, lineColor, depth);
}
from.onRollOver = Delegate.create(this, rollOn);
function rollOn() {
lineColor = 0xFF0000;
if (to._x == tox) {
drawLine(clipHome, from, to, lineColor, depth);
} else {
expander = _root.createEmptyMovieClip("expandro", 9998);
expander.attachMovie("expander", "exp", 9999);
expander._x = _xmouse;
expander._y = _ymouse-20;
}
}
from.onRollOut = Delegate.create(this, rollOff);
function rollOff() {
expander._x = -200;
expander._y = -200;
lineColor = 0x000000;
if (to._x == tox) {
drawLine(clipHome, from, to, lineColor, depth);
} else {
}
}
}
private function drawLine(clipHome:MovieClip, from:MovieClip, to:MovieClip, lineColor:Number, depth:Number):Void {
_root.onEnterFrame = function() {
lineClip = clipHome.createEmptyMovieClip("lineClip_"+depth, depth);
lineClip.lineStyle(5, lineColor, 40);
lineClip.moveTo(from._x, from._y);
lineClip.lineTo(to._x, to._y);
};
}
}


.FLA CODE:


Code:
var man_1_man2:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_2, man1Line, man_2x, man_2y, 1);
var man_1_man6:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_6, man1Line, man_6x, man_6y, 2);
var man_1_man8:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_8, man1Line, man_8x, man_8y,4);
var man_1_man9:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_9, man1Line, man_9x, man_9y,104);
var man_1_man10:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_10, man1Line, man_10x, man_10y,5);
var man_1_man14:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_14, man1Line, man_14x, man_14y,6);
var man_1_man15:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_15, man1Line, man_15x, man_15y,7);
var man_1_man16:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_16, man1Line, man_16x, man_16y,8);
var man_1_man19:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_19, man1Line, man_19x, man_19y,9);
var man_1_man21:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_21, man1Line, man_21x, man_21y,10);
var man_1_man23:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_23, man1Line, man_23x, man_23y,11);
var man_1_man26:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_26, man1Line, man_26x, man_26y,12);
var man_1_man27:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_27, man1Line, man_27x, man_27y,13);
var man_1_man28:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_28, man1Line, man_28x, man_28y,14);
var man_1_man29:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_29, man1Line, man_29x, man_29y,15);
var man_1_man30:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_30, man1Line, man_30x, man_30y,16);
var man_1_man33:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_33, man1Line, man_33x, man_33y,17);
var man_1_man34:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_34, man1Line, man_34x, man_34y,18);
var man_1_man36:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_36, man1Line, man_36x, man_36y,19);
var man_1_man37:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_37, man1Line, man_37x, man_37y,20);
var man_1_man48:connectAgent = new connectAgent(biggun, biggun.man_1, biggun.man_48, man1Line, man_48x, man_48y,21);

OnLoad, Scope, And Delegate
This has been addressed many times as I've searched though posts and threads online, but I still can't get this to work. I'm trying to populate an array that in the class's scope with values taken from a text file. Using delegate I'm able to get out of the onLoad scope and access the array in the class's scope. This leaves me unable to reference the variables taken from the text file.

I've looked at this webpage http://www.kirupa.com/web/xml/XMLspecificIssues3.htm. It says in the second to the last paragraph "Of course, you can also see that because the scope of the onLoad method is no longer within the XML instance and this represents the class, _xml has to be used in order to access content of the XML instance and what had been loaded." I've tried that my debug tells me there is no property someVariable nor menu_text.someVariable.


class Container extends MovieClip
{
var menu_items_array:Array = [];
public var test:String = "Class - test variable is working!";

public function Container()
{
var menu_text = new LoadVars();
menu_text.onLoad = Delegate.create(this, populate_menu);
menu_text.load("text/menu.txt");
}

public function populate_menu()
{
menu_items_array.push(menu_text.someVariable); //trying to get this to work
trace(test); //this works
trace(someVariable); //this doesn't work
trace(menu_text.someVariable); //this doesn't work either
}

}

I know this is an old problem. I just don't know the answer. Please help! Many, many thanks!

Add/remove EventListener W/delegate
Quick Question on removing Event Listeners

I created an event Listener w/ this:

close_btn.addEventListener("click",Delegate.create(this, closeApp));

and remove it with this:
close_btn.removeEventListener("click",Delegate.create(this, closeApp));

is this correct? and How do I know it has been removed?

Delegate Class Hack
I hesitate to post this as I know its not a preferred way of using this especially if you're building a flash app with strict Design Patterns. With that said, I really like using the Delegate Class, but as I've found a number of posts about not being able to pass an argument when using Delegate.create(obj,func);. I too wish there was some type of support for this (and I realize there are other ways of achieving this with Event handlers etc). Anywho, I have added to the Delegate class to support this. Getting the arg out is hacky, but for some very small classes I've build, it works well.

This is what I've added to the Delegate Class file:

ActionScript Code:
/**The Delegate class creates a function wrapper to let you run a function in the contextof the original object, rather than in the context of the second object, when you pass afunction from one object to another.*/class mx.utils.Delegate extends Object{    /**    Creates a functions wrapper for the original function so that it runs    in the provided context.    @parameter obj Context in which to run the function.    @paramater func Function to run.    //ADDED    @paramater args array to pass to Function.    */        static function create(obj:Object, func:Function, args:Array):Function    {            var f = function()        {            var target = arguments.callee.target;            var func = arguments.callee.func;            return func.apply(target, arguments);        };        f.target = obj;        f.func = func;                //ADDED function.args        f.args = args;                return f;    }    function Delegate(f:Function)    {        func = f;    }    private var func:Function;    function createDelegate(obj:Object):Function    {        return create(obj, func);    }}


And to retrieve args past, see this simple class

ActionScript Code:
import mx.utils.Delegate;class Foo {    private var __btn:MovieClip;    private var __name:String;    public function Foo(_b:MovieClip) {        __btn = _b;        init();    }        private function init() {        var myArgs:Array = ["one","two"];                //here I'm passing an array of items        __btn.onRelease = Delegate.create(this,clicker,myArgs);    }        private function clicker():Void {        //this is the hacky way to retrieve the args from arguments.caller        trace(arguments.caller.args);    }}


Hope this may be of some use to someone.

Mx.utils.Delegate.create
Hi,
I am using the mx.utils.Delegate.create class to run a function after an event listener is invoked such that:

datareceiver.onLoad = mx.utils.Delegate.create(this,dothis);

The dothis function executes properly, but datareceiver becomes unscopeable in the dothis function. datareceiver is receiving variables back from a php script, so I need access to datareceiver.returnData So, in the dothis function I want to do something like:

this.php_response.text = datareceiver.returnData;

How is this accomplished? and if you could provide a bit of theory behind it that would be great...TIA

AS2 Class Delegate Problem
Hi good people of Kirupa!

I'm writing a very simple class, which is meant to affect the movieClip "ball_mc". All I want it to do is to randomize its (ball_mc) properties (._alpha, ._x, ._y etc).


Code:
import mx.utils.Delegate;

class move {
private var t_mc:MovieClip;

public function move(t:MovieClip) {
t_mc = t;
randomize();

}

private function randomize():Void {
t_mc.onEnterFrame = function() {
this._x += randNum(-100, 100);
}
}

private function randNum(min:Number, max:Number):Number {
var n:Number = (min + Math.floor(Math.random() * (max - min)));
trace(n);
return n;
}

}
I guess this could be a job for Mr. Delegate, but I don't get it to work properly. The problem is that is won't call the randNum function, due to scoping issues I suspect. The "onEnterFrame" works fine.

Any hints guys? Thanks in advance.

Delegate Class Problem
I'm using the delegate class to allow my class variables to be referenced inside an xml.onLoad event. More specifically I'm calling a push on an array(which is a member of my class) in the onLoad event function. When I trace the array's length inside the event handler, it does indeed increase incrementally for each object pushed but when I try to trace outside the onLoad event handler it always outputs 0 as if I added nothing. Does anybody know why? I know I use the delegate class to fix the scope problem of the member array in the xml event but do I need to do something else to get the scope of the array back to the class? Or is something else going on?

Here's the relevant code:

Code:
import mx.utils.Delegate;
class League{
private var teams:Array;
private var xmlInput:XML;
public function getTeams():Array
{
var teamsArray:Array=new Array();
teamsArray=teams.slice();
return teamsArray;
}
private function loadTeams():Void
{
teams=new Array();
xmlInput=new XML();
xmlInput.ignoreWhite=true;
xmlInput.onLoad=Delegate.create(this, onTeamLoadEvent);
xmlInput.load("NFLTeamStats.xml");
}
private function onTeamLoadEvent(success:Boolean):Void
{
if(success)
{
for(var i=0; i<xmlInput.firstChild.childNodes.length; i++)
{
var t:Team=new Team(xmlInput.firstChild.childNodes[i].attributes.name,
xmlInput.firstChild.childNodes[i].attributes.totalGames,
xmlInput.firstChild.childNodes[i].attributes.wins,
xmlInput.firstChild.childNodes[i].attributes.losses,
xmlInput.firstChild.childNodes[i].attributes.pointsForPerGame,
xmlInput.firstChild.childNodes[i].attributes.yardsForPerGame,
xmlInput.firstChild.childNodes[i].attributes.thirdDownPercentage,
xmlInput.firstChild.childNodes[i].attributes.penaltyYards,
xmlInput.firstChild.childNodes[i].attributes.pointsAllowedPerGame,
xmlInput.firstChild.childNodes[i].attributes.yardsAllowedPerGame,
xmlInput.firstChild.childNodes[i].attributes.interceptions,
xmlInput.firstChild.childNodes[i].attributes.forcedFumbles,
xmlInput.firstChild.childNodes[i].attributes.puntReturnAvg,
xmlInput.firstChild.childNodes[i].attributes.kickReturnAvg);

teams.push(t);
}
}
}
}
I call the the loadTeams function in the constructor for this class.

Delegate A Setters Call In AS2?
Code:
_navComp.selectionCallback = Delegate.create( _codeHintsManager, _codeHintsManager.arrowUpCB, true );
Above is the code that i am currently using... I had to make a function because of the scope of my object. I would prefer using the _codeHintsManager.arrowUp (setter). But I can't get anything to work.


Code:
_navComp.selectionCallback = Delegate.create( _codeHintsManager, _codeHintsManager.arrowUp, true );
Above does not work... is there a way to do this without making callbacks?

Delegate Class Problem
I'm using the delegate class to allow my class variables to be referenced inside an xml.onLoad event. More specifically I'm calling a push on an array(which is a member of my class) in the onLoad event function. When I trace the array's length inside the event handler, it does indeed increase incrementally for each object pushed but when I try to trace outside the onLoad event handler it always outputs 0 as if I added nothing. Does anybody know why? I know I use the delegate class to fix the scope problem of the member array in the xml event but do I need to do something else to get the scope of the array back to the class? Or is something else going on?

Here's the relevant code:


Code:
import mx.utils.Delegate;

class League{

private var teams:Array;
private var xmlInput:XML;

public function getTeams():Array
{
var teamsArray:Array=new Array();
teamsArray=teams.slice();
return teamsArray;
}

private function loadTeams():Void
{
teams=new Array();
xmlInput=new XML();
xmlInput.ignoreWhite=true;
xmlInput.onLoad=Delegate.create(this, onTeamLoadEvent);
xmlInput.load("NFLTeamStats.xml");
}

private function onTeamLoadEvent(success:Boolean):Void
{
if(success)
{
for(var i=0; i<xmlInput.firstChild.childNodes.length; i++)
{
var t:Team=new Team(xmlInput.firstChild.childNodes[i].attributes.name,
xmlInput.firstChild.childNodes[i].attributes.totalGames,
xmlInput.firstChild.childNodes[i].attributes.wins,
xmlInput.firstChild.childNodes[i].attributes.losses,
xmlInput.firstChild.childNodes[i].attributes.pointsForPerGame,
xmlInput.firstChild.childNodes[i].attributes.yardsForPerGame,
xmlInput.firstChild.childNodes[i].attributes.thirdDownPercentage,
xmlInput.firstChild.childNodes[i].attributes.penaltyYards,
xmlInput.firstChild.childNodes[i].attributes.pointsAllowedPerGame,
xmlInput.firstChild.childNodes[i].attributes.yardsAllowedPerGame,
xmlInput.firstChild.childNodes[i].attributes.interceptions,
xmlInput.firstChild.childNodes[i].attributes.forcedFumbles,
xmlInput.firstChild.childNodes[i].attributes.puntReturnAvg,
xmlInput.firstChild.childNodes[i].attributes.kickReturnAvg);

teams.push(t);
}
}
}
}
I call the the loadTeams function in the constructor for this class.

Delegate Class Issue
I'm building a small Flash application that will essentially rotate ads for a home page and have run into an issue that I can't seem to get a handle on what's causing it.

I'm dynamically getting the ads that will show up in the player via an XML file, loads the file into a clip and sets a Delegate for the onRelease action to the clip, essentially making that clip become a button with an action to some other content deeper in the site.

I'm running into the problem with the Delegate class.  When I call it, setting it to a function that will handle getting the URL to go to and sending the user there, it is immediately executing that code and not waiting on the onRelease to occur first.

CODE    function _onAdsLoadInit($mc)
    {
        if (_isSmallVersion)
        {
            $mc._yscale = $mc._xscale;
        }
        var _maskNumber = _getRandomNumber(0, 4);
        var _movieClip = $mc._parent.attachMovie("movieMask" + _maskNumber, "mask", 2);
        $mc.setMask(_movieClip);
        var _parentId = $mc._parent.id;
        _carousel[_parentId].isLoaded = true;
        trace("_onAdsLoadInit: $mc._parent = " + $mc._parent);
        $mc._parent.onRelease = com.actionscript.utils.Delegate.create(this, _onClickAds(_parentId));
        if (_intervalElapsed && _parentId == this.__get__nextAd() && _isInited)
        {
            _nextReveal = nextAd;
            this._animateAdOut($mc);
        }
    }

    function _onClickAds($i)
    {
        trace("_onClickAds: $i = " + $i);
        var _webTrendsData = _sendWebTrendsData($i);
        if (com.nationwide.corporate.external.carousel.Constants.__get__IS_IN_BROWSER())
        {
            getURL(_carousel[$i].link);
        }
        else
        {
            trace("_onClickAds: Link = " + _carousel[$i].link);
            trace("_onClickAds: WebTrends = " + _webTrendsData);
        }
    }
    
    function _sendWebTrendsData($i)
    {
        /* TODO - Need to work with Bryan to get correct
        Web Trends information added to application */
        
        var _wtData = "javascript:dcsMultiTrack('DCS.dcsuri','" +
        com.nationwide.corporate.external.carousel.Constants.DCS_URI +
        "', 'WT.ti','" +
        _carousel[$i].wtname +
        "', 'WT.hpadclick','" +
        ++$i +
        "');";
        
        return(_wtData);
    }


Delegate.create() Issue
Hello:

I'm working with a class, linked with a movieclip, that is sort of indepent.

Say, my class has more or less this structure


ActionScript Code:
class myClass
{
   function myClass()
   {
       var mc = createEmptyMovieClip(....);
       //And now I need to attach this movieclips this way, since they are in a bucle and I dont know how many items there are...
      while()
      {
          i++;
          mc["item"+i] = attachMovieClip(...);
          //And now
          mc["item"+i].onRelease = myFunction;
 
       }
 
 
    }
   //This function is called when click on mc["item"+i]
   public function myFunction()
   {
 
    }
}


So you can see, when someone clicks on my mc["item"+i], myFunction is called in the scope of mc["item"+i] movieclip.


Now lets say I want to call myFunction from outside the class, BUT in the mc["item"+i] scope, where i is already a number.

Something like:


ActionScript Code:
Delegate.create(ObjectOfMyClass.mc["item"+i], ObjectOfMyClass.myFunction) ;


Should be able to call the function in scope, but unfortunately, is not working for me. Does anybody has any idea why is this wrong?

I hope everything is clear enough.

Thanks for reading.

[Delegate] - Scope Issue
Last edited by JRocket : 2006-10-05 at 11:06.
























Hello, all! I'm trying to get a function called "vlistOnLoad" to execute when vlist:XML 's onLoad event is fired. I can verify that it is referencing the correct XML file and data is being loaded.

Below is a simplified version of the frame code I'm using:

ActionScript Code:
import mx.utils.Delegate;
 
var vlist:XML = new XML();
    vlist.ignoreWhite = true;
    vlist.onLoad = Delegate.create(this, vlistOnLoad);
function vlistOnLoad()
    {
        trace("on load triggered");
}
vlist.load("../data/playlist.xml");


And yet, the vlistOnLoad function never gets called... I'm a at a loss.

[AS 2.0] Delegate.create + OnMetaData
Ok this should be a good one for you hardcore peeps. I'm using the good ol' Delegate.create to get around a scope issue with the XML onLoad event in a component I'm building. In another I'm trying to get around the same issue with the netStream class and the newer onMetaData event. If you don't know what that is no problem. My issue is with Delegate.

SO here is what I want to have:

Ok this should be a good one for you hardcore peeps. I'm using the good ol' Delegate.create to get around a scope issue with the XML onLoad event in a component I'm building. WORKS GREAT! THANK YOU MIKE!

In another I'm trying to get around the same issue with the netStream class and the newer onMetaData event. If you don't know what that is no problem. My issue is with Delegate. I want to pass a returned parameter from the event.

So here is what I want to have now:


ActionScript Code:
var scope:MovieClip = this
  VideoStream_ns.onMetaData = function(info:Object)
  {
   scope.VideoTotalTime = info.duration;
   scope.VideoRate = info.videodatarate;
   scope.VideoAudioRate = info.audiodatarate;
   scope.VideoCreationDate = info.creationdate;
   // i have to pass scope again to call another function in the class
  }


This is the easiest way around scope issues in AS2.0 but it is an endless trail of passing the scope around if you want to call more functions. So how do I pass the "info" object in the onMetaData event with the Delegate setup? Something like this...


ActionScript Code:
VideoStream_ns.onMetaData = Delegate.create(this, PopulateMetaData(info));
 
//............further down
 function PopulateMetaData(MetaData)
 {
   trace(MetaData)
   // use the object here
 }


Can you pass parameters? If so how can I pass one with Delegate and the onMetaData event? Think of it just like success or something when XML loads.

With the above I get this returned at compile time;

**Error**
Line 94: There is no property with the name 'info'.
VideoStream_ns.onMetaData = Delegate.create(this, PopulateMetaData(info));

Using The Delegate Class In Carousel
Im most certainly a novice when it comes to Actionscript, (maybe not even good enough to be considered a novice)

but i have a friend who has been professional programmer since the 1970's and i have introduced her to actionscript so that she may help me out.

She seems to think that the use of the Delegate class in the carousel tut is merely a work 'around and ideally the code should been strong-typed better so as not to require the delegate class.

I couldnt argue either way as i have a hard enough time understanding the rudimentary stuff. This friend of mine can be a bit obstinate at times so im not fully sure if she has it right.

can someone shine a bit of light on this? As it would help greatly.

thanks in advance
cressa

Delegate Button Component V2 & OnRelease
Hi I was wondering if it is possible to add a eventListener to a onRelease event using delegate on the button component v2.


something like
drag_btn.addEventListener("release", Delegate.create(this, btn_onRelease));

Call Function From Another Scope (delegate)
I am having trouble trying to call this whole routine (again) once a 'save button' is clicked (basically want to re-populate to reflect changes)

this already gets called ONCE (intitally) on the movie/project Load...

1.) I have tried to wrap the whole thing (routine) in a function, but then it stops working as it should (doesnt populate correctly, everything becomes 'undefined')

2.) I have tried pathing to the specific functions from my save button (located on _root)...but no go...(failed load)

here is the code (all of it) I need to 're-call' and run, when the save button is clicked.

thanks for anything I am missing:


Code:
import mx.utils.Delegate;
//
var rootNode:XMLNode;
var productsNode:Array;
var totalProducts:Number;
var myProducts_xml = new XML();
//
myProducts_xml.ignoreWhite = true;
myProducts_xml.onLoad = Delegate.create(this, getTotalProducts);
myProducts_xml.load("prodData/products.xml"); //local version
//myProducts_xml.load("prodData/products.xml?ran="+random(999999)); //web version (cache killer)

//
function getTotalProducts(success):Void {
if (success == true) {
rootNode = myProducts_xml.firstChild;
productsNode = rootNode.childNodes;
totalProducts = rootNode.childNodes.length;
createProducts();
this.onEnterFrame = Delegate.create(this, function() {
populateAll();
delete this.onEnterFrame;
}//end Function
); //end Delegate
}else {
trace("INIITIAL Load Failed");
}
}

//
function createProducts():Void {
//Define how many columns
var columns:Number = 1;
//Define the item vSpacing;
var vSpacing:Number = 10;
//Define the item hSpacing;
var hSpacing:Number = 0;
for (i=0; i<totalProducts; i++) {
var attachProduct:MovieClip = attachMovie("productEntry", "product"+i, i);
attachProduct._x += 10;
attachProduct._y += 0;
attachProduct._y += i * 45;
//attachProduct._y = Math.floor(i / columns) * hSpacing; //only used with multiple columns
//attachProduct._x = Math.floor(i % columns) * vSpacing; //only used with multiple columns
}
}

//populate
function populateAll():Void {
for (i = 0; i < totalProducts; i++) {
var totalQuantity:Number =productsNode[i].childNodes[7].childNodes.length;

//random data
var obj = this["product" + i];
obj.prodNum = i; //declaring what product (node) this is

//currentImage
var prodImage:String = productsNode[i].childNodes[0].firstChild.nodeValue;
var obj = this["product" + i];
obj.currentImage = prodImage;
//obj.currentImage = obj.currentImage.toUpperCase();
obj.currentImage = obj.currentImage.toLowerCase();

//name
var prodName:String = productsNode[i].childNodes[1].firstChild.nodeValue;
var obj = this["product" + i];
obj.name_txt.text = prodName +i;
obj.name_txt.text = obj.name_txt.text.toUpperCase();

//price
var prodPrice:Number = productsNode[i].childNodes[2].firstChild.nodeValue;
var obj = this["product" + i];
obj.selectedPrice = ["$"+prodPrice];
obj.price_txt.text = obj.selectedPrice;
//trace("PRICE :"+obj.selectedPrice);

//description
var prodDesc:String = productsNode[i].childNodes[5].firstChild.nodeValue;
var obj = this["product" + i];
obj.descriptionVar = prodDesc;
obj.descriptionVar = obj.descriptionVar.toUpperCase();
//obj.descriptionVar = obj.descriptionVar.toLowerCase();

//colors
var colorLength:Number =productsNode[i].childNodes[4].childNodes.length;
trace("Total Colors: "+colorLength);
for (z = 0; z < colorLength; z++) {
var totalColors:Array =productsNode[i].childNodes[4].childNodes[z].firstChild.nodeValue;
var obj = this["product" + i];
obj.colorChoices.push(totalColors);
}
//sizes
var sizeLength:Number =productsNode[i].childNodes[3].childNodes.length;
trace("Total Sizes: "+sizeLength);
for (y = 0; y < sizeLength; y++) {
var totalSizes:Array =productsNode[i].childNodes[3].childNodes[y].firstChild.nodeValue;
var obj = this["product" + i];
obj.sizeChoices.push(totalSizes);
}
trace("Color Array: "+obj.colorChoices);
trace("Size Array: "+obj.sizeChoices);
trace(newline);
}
}

[F8] Multiple Listeners With Delegate Class
Hi there.

Trying to get to grips with the Delegate class. How do I resolve the scope issue with the interval. It can't access the class's variables.


Code:
private var sliderIntervalID:Number;
private var itemIndex:Number

targetScrollbar.slider_mc.addEventListener("onPress", Delegate.create(sliderPressed));

targetScrollbar.slider_mc.addEventListener("onRelease", Delegate.create(sliderReleased));

private function sliderPressed():Void {
targetScrollBar.startDrag(//This is not the problem);
sliderIntervalID = setInterval(myInterval, 100);
}

private function sliderReleased():Void{
targetScrollBar.stopDrag();
clearInterval(sliderIntervalID);
}

private function myInterval():Void{
trace(itemIndex);
}


Thanks

Trying To Cast A Member With Delegate - Need A Hand
Hi Guys,

Check this out.
Ive got a class that I call using the following.
This line moves my menu up.
button.addEventListener('release', Delegate.create(this, toggling.menuUp));
Works fine.

I want to move my menu up into a certain position hence I write
button.addEventListener('release', Delegate.create(this, toggling.menuUp(3)));

and it never works when I try to cast something in this way. All my vars and members are accessible. Let me know if you need more code for explanation on this. Just want to know is it possible to cast using this process?

Problem With Scope Using Delegate.create()
I'm working on a class where I have a method that creates a number of MovieClips as children of a Container movieclip.

I need to pass on some of the events (like onRelease) from each of these child-movieclips to the class, i.e. to a listener attached to the instantiated object of that class, so that I can trap these events in my application and perform the desired actions.

Furthermore, I need to pass a reference to that particular movieclip to the event handler, so that I know which movieclip triggered the event.

If I use Delegate.create(), I receive the event fine, but I have no knowledge in that event handler of which movieclip caused the event to fire. If I don't use Delegate.create(), I can't seem to catch the event, leaving me clueless.

Can anyone help me out here ? I'm in a little bit of a time squeeze, so I'm hoping for a really quick response!

Thanks in advance!

- mortenft

EventDispatcher And Delegate Syntax Problem
So -- I found, from a co-worker, a novel way to handle a lot of EventDispatcher events from a class instance talking back to the main timeline, using the Delegate class. I'm not sure if it's kosher, but it seems to work...unless I goof up the syntax when I set it up.

Here's the code that works:


Code:
itemsDelegate = Delegate.create(this, itemsChange);
function itemsChange(evt_obj:Object):Void
{
switch(evt_obj.type)
{
case "answer" :
trace("Answer selected : " + evt_obj.answer);
break;
default :
// do nothing for default case
break;
}
}

queItemClip.addEventListener("answer", itemsDelegate);
I can fire off, from the that class instance (queItemClip) as many event types as I need and use the switch case to handle them all. Just a variation of writing the event listeners, I guess.

However, I can't get it to work if I write the code block this way:


Code:
itemsDelegate = Delegate.create(this, itemsChange);
this.itemsChange = function(evt_obj:Object):Void
{
switch(evt_obj.type)
{
case "answer" :
trace("Answer selected : " + evt_obj.answer);
break;
default :
// do nothing for default case
break;
}
}

queItemClip.addEventListener("answer", itemsDelegate);
Why does the named function variant work and the anonymous function fail? Keep in mind, I'm writing the anonymous function variant differently than...


Code:
var itemsChange:Function = function(evt_obj:Object):Void {}
Is it a scope issue?

Thanks,
IronChefMorimoto

Loosing The Scope And Delegate Is Not Helping Either
Hi Guys,

I'm breaking my head to make this work.
What I want to do is after the xml has loaded
to load an image in a movieClip.
Plase note that the filenameLoader Class
is an extension of the xml class and returns
an array "getPaths()" which contains the names of the images.
So as you understand is importand that the loadClip runs after
the xml has loaded.
The problem in the class bellow is that the:

loader_mcl.loadClip(myXML.getPaths()[0], picHolder);

is loosing the scope.
How can I fix this? Any ideas?


ActionScript Code:
class imageLoader extends MovieClip {
    var picHolder:MovieClip;
    var frameHolder:MovieClip;
    var picWidth:Number;
    var picHeight:Number;
    var loaded:Boolean = false;
    var myXML:filenameLoader;
    private var loader_mcl:MovieClipLoader;

////////////////////////////////////////////////////////////////////////////////// 
   
    function imageLoader() {
       
        loader_mcl = new MovieClipLoader();
        picHolder = this.createEmptyMovieClip("picture", 0);
        loader_mcl.addListener(this);
        myXML = new filenameLoader("featuredimages.xml");
       
        myXML.onLoad = function() {
                trace(myXML.getPaths());
                loader_mcl.loadClip(myXML.getPaths()[0], picHolder);               
};
       
    }
   
//////////////////////////////////////////////////////////////////////////////////   
   
    function rR(y:Number, x:Number):Number {
        var z:Number = Math.round(Math.random()*(y-x))+x;
        return z;
    }
    private function onLoadInit(target:MovieClip):Void {
        new Smoothing(target);
        loaded = true;
        trace("clip has finished loading");
        picWidth = target._width;
        picHeight = target._height;
        //trace(picWidth+" "+picHeight);
        frameGenerator();
        //shadowClass.addShadow(frameHolder);
    }
    public function onLoadProgress(target:MovieClip, bytesLoaded:Number, bytesTotal:Number):Void {
        // trace(target + ".onLoadProgress with " + bytesLoaded + " bytes of " + bytesTotal);
    }
    public function frameGenerator() {
        frameHolder = this.createEmptyMovieClip("frame", -1);
        frameHolder.lineStyle(1, 0x00000);
        frameHolder.beginFill(0x000000, 100);
        frameHolder.moveTo(-10, -10);
        frameHolder.lineTo(picWidth+10, -10);
        frameHolder.lineTo(picWidth+10, picHeight+10);
        frameHolder.lineTo(-10, picHeight+10);
        frameHolder.lineTo(-10, -10);
        frameHolder.endFill();
    }
}

thanks a lot in advance.

Class File, Scope And Delegate
Hello -

I am having issues with an onPress function within a function in a class file in Actionscript 2. The issue is that the variables arent available within the onPress function.

Research has led me to the delegate class, but i am unsuccessful in getting it to work after many tries. Any help is appreciated.

This reutrns a value read in from an xml file:
(feeder.feed[i]["pdf"])

Here is the code that returns undefined:

["btn"+i].bck.onPress = function(){
_root.test.text = "this is the value: "+(feeder.feed[i]["pdf"]);
}

This is my implementation of the delegate class, which doesn't fire at all.

import mx.utils.Delegate;

function holdValue(){
_root.test.text = "a value: "+(feeder.feed[i]["pdf"]);
}

tgt["btn"+i].bck.onPress = Delegate.create(this, holdValue);

This seems like it should be staightforward but i have never used the delegate class before.

thanks in advance.

Mx.utils.Delegate And Static Functions
How can I get around using an instance variable in a static function that must be called by the Delegate method?

Anyone?

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