我正在尝试使下面的代码可重用。我的flash项目中需要多个切换按钮。现在,下面的代码适用于一个按钮。如果我继续创建更多按钮,并按照下面的格式,我需要为每个按钮创建单独的功能。
我想将可重用代码放在单独的ActionScript文件中,而不是放在FLA文件中。我正在尝试将rolloverToggle,rolloverToggle和toggleClick放在我正在制作的类中。
// ///////////////////////////////////////////////////////////////////////
// ------- Need to make this code reusable -------
// ///////////////////////////////////////////////////////////////////////
// code on Frame 1
toggleButton.addEventListener(MouseEvent.MOUSE_OVER, rolloverToggle);
toggleButton.addEventListener(MouseEvent.MOUSE_OUT, rolloutToggle);
toggleButton.addEventListener(MouseEvent.CLICK, toggleClick);
toggleButton.buttonState = "off";
// function rolloverToggle
function rolloverToggle(event:MouseEvent) {
toggleButton.gotoAndStop(toggleButton.buttonState+" over");
}
// function rolloutToggle
function rolloutToggle(event:MouseEvent) {
toggleButton.gotoAndStop(toggleButton.buttonState);
}
// function toggleClick
function toggleClick(event:MouseEvent) {
if (toggleButton.buttonState == "on") {
toggleButton.buttonState = "off";
toggleButton.gotoAndStop(1);
} else {
toggleButton.buttonState = "on";
}
}
答案 0 :(得分:1)
这很简单。创建一个新的通用按钮类,并在其中添加所有事件侦听器。对于您要创建的每个新按钮,只需扩展通用按钮并在事件侦听器中填写所需的代码。:
class GenericToggleButton extends Button
{
public GenericToggleButton()
{
this.addEventListener(MouseEvent.MOUSE_OVER, rolloverToggle);
this.addEventListener(MouseEvent.MOUSE_OUT, rolloutToggle);
this.addEventListener(MouseEvent.MOUSE_CLICK, toggleClick);
}
protected function rolloverToggle(event:MouseEvent):void
{
this.gotoAndStop(this.buttonState+" over");
}
protected function rolloutToggle(event:MouseEvent):void
{
this.gotoAndStop(this.buttonState);
}
protected function toggleClick(event:MouseEvent):void
{
if (this.buttonState == "on") {
this.buttonState = "off";
this.gotoAndStop(1);
} else {
this.buttonState = "on";
}
}
}
现在只需扩展该类并添加您的功能。
class NewButton extends GenericToggleButton
{
public NewButton()
{
super();
}
override protected function toggleClick(event:MouseEvent):void
{
super.toggleClick(event);
// do magic for this button
}
// ETC
}