Im going to post little AS tricks here when I think of them, to learn and have here for reference. Off-hand I cant really pull them off of the top of my head, but they come to me when I need them in coding. When that happens Ill come back and post anything thats considerably ‘tricky’ enough to be posted here.
Right now Ill do Daisychaining and callbacks. These I know now because I used them recently
Daisychaining
Though not the technical term (I dont think - its just what I call it) daisychaining is the act of throwing a bunch of methods on the end of an object (and each other) to have them all called in one line of code. Ex:
objClass = function(name, value){
this.name = name;
this.value = value;
};
objClass.prototype.showName = function(){
trace(this.name);
return this;
};
objClass.prototype.showValue = function(){
trace(this.value);
return this;
};
objInstance = new objClass("cletus",12).showName().showValue();
// outputs "cletus" and "12".
The trick lies in returning the object, this in the prototype functions. Then, when called, the action is executed and the object is returned. When returned, the next method is executed on the returned value which is the object itself.
Chances are you’ve seen this before with the easy version of a string replace: str.split().join(); I used it here on Kirupa in the Gaming battle creating and drawing objects in on the screen (and instantly adding onEnterFrame events to dynamically created objects).
Callbacks
These are functions associated with an event. When the event is triggered, the callback function is run in responce. Setting an onMouseDown function is setting a callback function. However, you can also incorporate such functions into your own code allowing you to set a temporary set of instructions to be run at a later time. A simple example of this can be implemented in a tweened or multi-framed transition. Lets say you have about 6 or so pages of content in your movie and a small animation leading up to and leading out of each page. In moving from page to page you have to not just goto the new page but play out of the current. What you could do is set your buttons in each page to play() the exit animation and set up a callback function which is to be run at the end of that animation. Example:
// button
on(release){
action = function(){
_root.gotoAndPlay("page2_label");
};
play();
};
// last frame
action();
Now certainly, in that simple example you could just set a variable and throw it in a gotoAndPlay at the end of the animation, but this allows for many actions to occur which can be similar or vastly different (if anything at all) from any other set callback functions. I used it here on Kirupa in the XML menu example using a callback menu to open the next menu section after closing the current.