AS3 question - Best way to lockout buttons
Hello and thanks for reading this. I made buttons using as3 within flash but what I'd like to do is make them inactive for a fe开发者_如何转开发w seconds when one is pressed. Normally I'd use google to solve this kind of a problem but I dont even know how to word it properly. Thanks
You could :
- Set the .enabled property to false in order to have your click event handlers disabled.
- Add a new locking variable and surround all the code in your click handler with 'if(lockingVariable)'. Then all you would need to do is set this to false. Ideally, though, you'd just disable the button.
As for doing it for a few seconds, look into the timer class. This link should be helpful. The typical pattern goes something like this :
var myTimer:Timer = new Timer(1000, 1); // 1 second
myTimer.addEventListener(TimerEvent.TIMER, runOnce);
myTimer.start();
function runOnce(event:TimerEvent):void {
trace("runOnce() called @ " + getTimer() + " ms");
}
All you would have to do is have a re-enabling callback as the method for line 2 and your button would be disabled for 1 second.
Try using this as a base class for your buttons:
package
{
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.Event;
public class MyButton extends SimpleButton
{
// vars
public const DELAY:uint = 30;
private var _timer:int = 0;
/**
* Constructor
*/
public function MyButton()
{
addEventListener(MouseEvent.CLICK, _click);
}
/**
* Called on Event.ENTER_FRAME
*/
private function _handle(e:Event):void
{
_timer --;
if(_timer < 1) removeEventListener(Event.ENTER_FRAME, _handle);
}
/**
* Called on MouseEvent.CLICK
*/
private function _click(e:MouseEvent):void
{
if(_timer > 0) return;
_timer = DELAY;
addEventListener(Event.ENTER_FRAME, _handle);
// do your stuff below
clickAction();
}
/**
* Override this and fill with your actions
*/
protected function clickAction():void
{
trace("override me");
}
}
}
Here's an example of overriding the clickAction()
method in MyButton:
package
{
public class MyPlayButton extends MyButton
{
override protected function clickAction():void
{
trace("play button clicked");
}
}
}
The way I would do it is simply set the enabled
property of the button to false
for a set amount of time, using a Timer
, once the button is pressed.
myBut.addEventListener(MouseEvent.CLICK, doStuff);
function doStuff(e:MouseEvent){
//write whatever the button does here
disableBut();
}
function disableBut(){
myBut.enabled = false;
var timer:Timer = new Timer(3000, 1);
timer.addEventListener(TimerEvent.TIMER, enableBut);
timer.start()
}
function enableBut(e:TimerEvent){
myBut.enabled = true;
}
Remember that the length of time that the button is disabled for is set in the first parameter of the Timer()
constructor, and is in milliseconds. In my example you can see that myBut
is disabled for 3 seconds.
精彩评论