views:

61

answers:

3

I am working with URLLoader and URLRequest in this case.

I have two buttons. One listens for the mouse click event and then runs the following function (less code not applicable to this question):

function loadURL (e:MouseEvent):void {

    ....

    var myRequest:URLRequest=new URLRequest("*URL*");
    myRequest.method=URLRequestMethod.POST;
    myRequest.data=postVars;

    var myLoader:URLLoader = new URLLoader();
    myLoader.load(myRequest);

    ....

}

The other button, when clicked, calls another function, say resetAll, that then resets the "session" by clearing out all the current variables and canceling anything currently in progress. Within that function I want to call myLoader.close(myRequest); but myLoader is not accessible from within resetAll.

In this case, should I declare var myRequest:URLRequest=new URLRequest("*URL*"); and var myLoader:URLLoader = new URLLoader(); outside of the function even if I do not need them yet?

I think I am missing some common sense knowledge of AS3 here, but not sure what it is. It would be appreciated if someone could fill me in on best practice in this case.

A: 

if this function is executed only once, you can use the variables from inside the function. if this function is executed more then once in the life-time of the application you should declare the variables once and then only reconfigure or reinstantiate them.

Another thing, if you need to use those variables outside the function then you should of course declare them globally. (resetAll)

Avi Tzurel
Thank you for your answer. What do you mean by "if this function is executed only once"?
Structure
If the execution of this function is a one time thing in your application (on creation complete for example)if it's executed repeatedly on user request or other application logic, you should use Global Variables.
Avi Tzurel
+2  A: 

You can declare URLLoader variable globally and use local declaration or URLRequest variable.

URLRequest is anyway you have to recreate for every new requests, declaring them locally would be more safer for GC to collect it after its use.

URLLoader makes no sence re creating everytime, you can just pass new URLReqest object into Load method everytime you want to load something from server.

Bhavesh.Bagadiya
A: 

In some cases, closures are very useful. (Especially, for handling events or for controlling asynchronous codes.) You can keep all the references of local variables at a time. But when the source code of closures goes huge in the function, you should think about moving them into another class.

Here is an example

Closure Example - wonderfl build flash online

One thing you may think is the cost of the closures. Executing closures costs much more than usual codes but it's negligible for ordinal cases.

9re