views:

86

answers:

1

I'm trying to make the code below reusable. I need multiple toggle buttons in my flash project. Right now the code below works on one button. If I continue and create more buttons, and follow the format below, I would need to create separate functions for each button.

I would like to put the reusable code in a separate ActionScript file and not in the FLA file. I am trying to put the rolloverToggle, rolloverToggle, and toggleClick in a class that I'm making.

// ///////////////////////////////////////////////////////////////////////

// ------- 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";    
        }
}
A: 

This is quite Simple. Create a new generic button class, and add all of your event listeners within. For each new button you want to create, just extend your generic button and fill in the required code within the event listeners.:

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";
        }
    }
}

Now just extend that class and add your functionality.

class NewButton extends GenericToggleButton
{
    public NewButton()
    {
        super();
    }

    override protected function toggleClick(event:MouseEvent):void
    { 
        super.toggleClick(event);

        // do magic for this button
    }

    // ETC
}
clownbaby