Please note that ExpatTech no longer operates regular office hours, meeting is by appointment only. Please call +36306031104 for details.

ExpatTech Techblog

Peter Todd 2010.08.03. 14:53

Flash Cookbook - Tricks - Global functions

Previously we wrote about global variables.

Going further, sometimes it's really useful to reach a certain function from a child of the child of the grandchild's child. Especially if we want to reach different functions from different objects. Imagine you have a url request in a certain object, and a sharedobject request in another, but somehow you need to reach both in a completely innocent small object somewhere in the depth of the jungle of the objects.

Therefore we add a new static variable to our global class, let's say we want to have a global message function:

public static var showMessage:Function;

Then at the initialization time, we assign the specific object's function to this variable:

Vars.showMessage = this.showMessage;

Done. Now, if this is done, you can reach this message function from anywhere (after importing your global class).

For understanding the practical reason to do this, let's see this message function. If we would like to show a message from an object and our gui handler is on the top of all objects, then we should dispatch a bubbling event, catch this event on the top and then get a messagecode from the invoker object to recognize the message. Event dispatching - listening - reading a property. Instead, we directly call the function with a messagecode.

Not even talking about an interesting phenomenon: if our class is extending a MovieClip, dispatching an event only works if the object is added to a displayobject. Horrible.

Now comes the question: why on earth should we use events? Good question, Young Padawan. Good question. Consider that firing and catching an event is practically the same as written above: you define an event and pair a function to this event. Then, whenever the event occurs, the function is called. In Flash mostly an event's target is the object itself, so you can reach it's properties.

But when you want to "cross-link" objects and share the same function among different objects, the method above might be useful.

Brilliant.

(reference tag: singleton)