- But what about reusability?
- To give a clip subclass to another developer, we'd have to pass the subclass code *and* the library symbol
- We could put the code on frame 1 of the symbol, but that creates problems:
- The clip code runs after the code on the frame where the instance is placed, meaning that methods/properties aren't available until the next frame.
- The code runs once for every instance attached.
- In flash 6, these problems are addressed by the #initclip directive, which specifies a block of code to run only once per symbol, before the first instance of that symbol is created.
- Here's the same Ball subclass, but this time created on frame 1 of the ballSymbol movie clip. Note the #initclip and #endinitclip directives. You can download a working .fla here.
#initclip
// Class
function Ball () {
this.setColor(this.theColor);
}
Ball.prototype = new MovieClip();
Object.registerClass("ballSymbol", Ball);
// Methods
Ball.prototype.setColor = function (newColor) {
var ballColor = new Color(this);
ballColor.setRGB(newColor);
}
Ball.prototype.startMoving = function (moveAmount) {
this.onEnterFrame = function () {
this._x += moveAmount;
}
}
Ball.prototype.stopMoving = function () {
delete this.onEnterFrame;
}
#endinitclip
- Now we can drag ballSymbol from one library to another, and create instances of Ball from any timeline:
// Make an instance.
this.attachMovie("ballSymbol", "blueBall", 1, { theColor: 0x0000FF });
// Call a method.
this.blueBall.startMoving(5);
- But what about instances created manually at author-time?
- When an instance is placed on Stage manually, its constructor still executes at run-time.
- However, the initObj can no longer be used to pass parameters to the constructor.
- Solution: add component parameters via Library >> Options >> Component Definition.
- Component parameters are instance properties set via the Properties inspector.
- Component parameters are defined before the constructor runs.
- Final picture of modular, reusable movie components:
- movie clip subclass (registerClass)
- defined inside movie clip symbol (#initclip)
- parameters specified through Properties inspector or initObj