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








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




ActionScript.org Forums > ActionScript Forums Group > ActionScript 2.0
Posted on: 01-15-2007, 02:02 PM


View Complete Forum Thread with Replies

Sponsored Links:

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

View Replies !    View Related
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.

View Replies !    View Related
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?

View Replies !    View Related
Mx.utils.Delegate Error With Carousel Tut 2 (class Path)
Somehow I think I have messed up my class path or something :?
When I test the .swf I get the following on my output monitor.

DataMacromediaFlash 8enConfigurationClassesmxutilsDelegate.as: Line 14: The name of this class, 'mx.utils.Delegate', conflicts with the name of another class that was loaded, 'mx.utils.Delegate'.
class mx.utils.Delegate extends Object

View Replies !    View Related
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

View Replies !    View Related
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.

View Replies !    View Related
[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));

View Replies !    View Related
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

View Replies !    View Related
Delegate.create() Vs Function.apply()
I see them both being pretty much the same. They basically call a function within a specified scope. Any ideas what any difference is?

View Replies !    View Related
AS2.0 Delegate.create Issues With Twen
Hi all. I'm using the tween class in several components. In one component the call back works fine.

ActionScript Code:
MenuListener.onMotionFinished = Delegate.create(this, OnButtonAnimationFinish);

But in another it won't fire written the same way.


ActionScript Code:
VideoCurtianListener.onMotionFinished = Delegate.create(this, OnCurtianFadeFinish);


But if I write it like this:


ActionScript Code:
VideoCurtianListener.onMotionFinished = Delegate.create(this, OnCurtianFadeFinish[u][b]()[/b][/u]);


then it will fire.

What could possibly cause this?? Can I not have 2 seperate objects listening for 2 seperate onMotionFinished events in 2 seperate components. It makes no sense whatsoever.

View Replies !    View Related
Delegate.Create For An Mc Inside A Class [DEADLINE] Pls Help
PHP Code:




import mx.events.EventDispatcher;
import mx.utils.Delegate;

class main_movie extends MovieClip
{
    public var pbSend:Button;
    public var my_mc:MovieClip;
    public var my_button:MovieClip;

    // constructor
    public function main_movie()
    {
        super();
        EventDispatcher.initialize(this);
        my_mc = attachMovie ("my_mc", "my_mc", getNextHighestDepth(), {_x :100, _y:50} );
        my_button = attachMovie ("my_button", "my_button", getNextHighestDepth(), {_x :100, _y:50} );
        my_button._x = 100;

        // I want to avoid doing this function here..
        /*this.onLoad = function()
        {
            // this is the only line that works and it does add the event.
            pbSend.addEventListener("click", Delegate.create(this, checkFields));

            // doesn't work
            my_mc.addEventListener("onRelease", Delegate.create(this, checkFields));

            // doesn't work
            my_button.addEventListener("onRelease", Delegate.create(this, checkFields));
        }*/


        //this["my_mc"].addEventListener("click", Delegate.create(this, checkFields));
    }

    // I would rather do it here...
    private function onLoad ()
    {
        // doesn't work, this line doesn't work in the onLoad function if its placed here !
        //pbSend.addEventListener("click", Delegate.create(this, checkFields));

        // doesn't work This is the most important one I really need to get it to work
        my_mc.addEventListener("onRelease", Delegate.create(this, checkFields));

        // doesn't work
        my_button.addEventListener("onRelease", Delegate.create(this, checkFields));
    }

    private function checkFields():Void
    {
            trace("check");
    }
}








Hi I need help, all I want to do is to create an onRelease event for the my_mc
clip which is being attached within the main_movie class.

it works for the button component but not for the mc clip... please advice

thanks

View Replies !    View Related
Utils: ExecuteAfterPause
Just thought I would post this method in case someone finds it useful. I am sure a lot of you have written something similar Basically, it's a wrapper for setInterval, which allows you to execute a method a given number of times. It returns an object which has a "cancel" method, allowing you to cancel execution without having to bother with intervalIds. I use it it quite often.


Code:
// returns the execution scope, containing a "cancel" method
// times=0 will execute infinite number of times
function executeAfterPause(scope:Object, func:Function, params:Array, secs:Number, times:Number, startRightAway:Boolean):Object {
// trace("executing func after " + secs + " secs " + (times?"infinite":times) + " number of times.");
if (times == undefined) {
// execute once by default
times = 1;
}

if (startRightAway) {
func.apply(scope, params);
if (times == 1) {
return;
} else if (times != 0) {
times--;
}
}

var exeScope:Object = new Object();
exeScope.scope = scope;
exeScope.func = func;
exeScope.params = params;
exeScope.timesLimit = times;
exeScope.t = 0;
exeScope.exe = function() {
// trace("applying " + this.func + " to " + this.scope);
this.func.apply(this.scope, this.params);
this.t += 1;
if ((this.timesLimit > 0) && (this.t >= this.timesLimit)) {
this.cancel();
}

}

// workaround for FP7 garbage collection bug (exeScope is collected)
// exeScope.intervalId = setInterval(exeScope, "exe", secs*1000);
exeScope.intervalId = setInterval(mx.utils.Delegate.create(exeScope, exeScope.exe), secs*1000);

exeScope.cancel = function() {
// invalid is needed not to clear the interval later
// (this intervalId might already refer to another interval)
if (!this.invalid) {
clearInterval(this.intervalId);
this.invalid = true;
}
}

return exeScope;
}
Following Headshotz's advice, adding this short tutorial:


Code:
class Test {
var objectVar:String = "objectVar";

function func(param1:String, param2:String) {
trace("executed! param1: " + param1 + ", param2: " + param2);
}

function objectFunc() {
trace(this.objectVar);
}


}

var test:Test = new Test();

// the following will print "executed! param1: hey, param2: ho" 2 times -
// 1 second after the invocation and 2 seconds after the invocation
executeAfterPause(test, test.func, ["hey", "ho"], 1, 2);

// the following will print "executed! param1: hey, param2: ho" 3 times -
// right away, 1 second after the invocation and 2 seconds after the invocation
// Note that null can be used for the scope here because test.func does not make use of any object
// vars of the Test class
executeAfterPause(null, test.func, ["hey", "ho"], 1, 3, true);

// the following will print "objectVar" once
// 5 seconds after the invocation
executeAfterPause(test, test.objectFunc, [], 5);

// this will keep printing "objectVar" indefinitely, every 5 seconds,
// starting right away, until scope.cancel() is called.
// Note that specifying "0" for times is interpreted as "execute an infinite number of times"
var scope:Object = executeAfterPause(test, test.objectFunc, [], 5, 0, true);

// (previous example continued) ... later
// Will stop printing "objectVar"
scope.cancel();

View Replies !    View Related
Mx.utils.Iterator
While looking at interface mx.data.to.ValueListIterator I noted that it extends mx.utils.Iterator, but the Iterator.as is not available!

Does anybody know where to get info about package mx.utils.*?

View Replies !    View Related
Math.Utils? Or NumberPlus.as?
I have a script that is running slowly that is having to perform a lot of calculations, many of which result in a number something like:
0.0028462385867362854-E
and I'm wondering if this isn't part of my problem. It seems like having to do a calculation on a 15 digit number rather than a 4 or 5 digit number would slow things down, but maybe not? If all of these numbers were truncated to the thousandth place, like:
0.003 in the above example would that affect my playback speed? I'm guessing that it would, but then would the extra calculations I'd have to do to round every damn number in the script offset that speed savings?
Is this making sense!?

Has anyone run into/thought about/dealt with this? I've thought of two solutions:
1) Extend the Number class and make every number round itself off. Don't know if this would work, don't know if it would add too many extra processes.
2) Define a Math.Util that does this and then apply it every time I make a calculation. I don't like this one so much, for obvious reasons.

Thanks for taking the time to ponder this.

R

View Replies !    View Related
CS3 Can't Find Flash.utils
The utilities that you commonly import at the top of your packages like:

import flash.utils.getDefinitionByName;

My CS3 is not able to find all these.

Where are these files supposed to be stored, and how can I set the path for my CS3 so it always finds them (no matter what folder I am working in)?

View Replies !    View Related
Testing For Higher Res Utils?
ok-
so I've been messing with a lot of full-window flash stuff recently, but my laptop maxes out at 1280x800. any ideas for testing for high resolutions on my machine? (the ie zoom thing doesn't really cut it....)

t

View Replies !    View Related
Can Someone Explain Mx.utils.Collection Usage?
i don't understand this class or it's purpose/function? there is no real explanation in Live Docs either. Can anyone offer any info?

thanks in advance...

View Replies !    View Related
Flash.utils.Dictionary Source
Hi there,
any chances to see the source code of the Dictionary class? if not a possible reconstruction of it?

I have to work with as2, and i'm porting some as3 code. I figure that a Dictionary is some sort of Map, it saves a relation between two objects, key and value. If you pas it a key, you get the value for it and so on.

But i would like to understand the particularities of Dictionary...

perhaps a good paper/tutorial about it.

regards, goliatone.

View Replies !    View Related
Com.leebrimelow.utils.AnimatedButton Error
Ok someone on here built me an MP3 player in Flash 8 and sent me all the files, as I only have MX 2004 the .fla would not open. Someone else on the forum then opened it in CC3 saved for Flash 8 then opened it in Flash 8 and saved for MX 2004... so now I can edit the .fla but when I go to export movie I get this error:

Code:

**Error** Symbol=next, layer=icons, frame=1:Line 1: The class 'com.leebrimelow.utils.AnimatedButton' could not be loaded.

Total ActionScript Errors: 1     Reported Errors: 1

The movie does actually work fine but I would still like to fix this error. I have attached the MP3 player (MX 2004 format, which I need!)

View Replies !    View Related
The Class Or Interface 'flash.utils.ByteArray' Could Not Be Loaded.
Hi all, I am trying to use some of the new functionality that is available in AS3 and I keep getting an unfathomable error message. The code that I am using is at the bottom of this post.

No matter what I do I keep getting the following error when I compile this code

The class or interface 'flash.utils.ByteArray' could not be loaded.

And the source line is

var pixels:ByteArray = srcBmp.getPixels( new Rectangle(0,0,imageWidth,imageHeight) );

Can anybody see what I am doing wrong here? This is driving me crazy!!










Attach Code

import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Rectangle;
import flash.utils.ByteArray;

var imageWidth:uint = Elems.GroundMC.width;
var imageHeight:uint = Elems.GroundMC.height;

var srcBmp:BitmapData = new BitmapData( imageWidth, imageHeight );
srcBmp.draw( Elems.GroundMC );

var pixels:ByteArray = srcBmp.getPixels( new Rectangle(0,0,imageWidth,imageHeight) );
var copyBmp:BitmapData = new BitmapData( imageWidth, imageHeight, true );

View Replies !    View Related
Request Concerning Flash Installation Files (utils Classes)
can someone (or many ones) open up their
[flash install]/[language]/First Run/Classes/mx/utils
directory and tell me whats in there? Also, if you have any other Flash-related applications installed, can you also mention them?

I personally only have Delegate.as there. The only other Flash-related application I have installed is Swift 3D (with importer)

Thanks

View Replies !    View Related
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!

View Replies !    View Related
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"?

View Replies !    View Related
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?

View Replies !    View Related
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.

View Replies !    View Related
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.

View Replies !    View Related
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

View Replies !    View Related
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.

View Replies !    View Related
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

View Replies !    View Related
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

View Replies !    View Related
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.

View Replies !    View Related
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

View Replies !    View Related
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

View Replies !    View Related
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.

View Replies !    View Related
[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

View Replies !    View Related
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

View Replies !    View Related
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.

View Replies !    View Related
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?

View Replies !    View Related
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!

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

View Replies !    View Related
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?

View Replies !    View Related
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

View Replies !    View Related
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?

View Replies !    View Related
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.

View Replies !    View Related
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);

View Replies !    View Related
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!

View Replies !    View Related
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?

View Replies !    View Related
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.

View Replies !    View Related
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.

View Replies !    View Related
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.

View Replies !    View Related
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?

View Replies !    View Related
Copyright © 2005-08 www.BigResource.com, All rights reserved