AS3: startDrag firing mouse_up/mouse_click events
As I started developing mobile apps for iOS/Android using Adobe AIR I encountered strange problem (or feature).
开发者_高级运维If you create Sprite and make it draggable using startDrag/stopDrag inside MOUSE_DOWN/MOUSE_UP event handlers, everything works. But if you add another listener MOUSE_CLICK to the same object, it starts to fire together with MOUSE_UP. Logically this behavior is all right. What I need is to prevent firing MOUSE_CLICK handler when user drags the Sprite (startDrag) and I need it to fire when user did not drag the Sprite.
What I'm trying to create is a small thumbnail bar which is draggable and after clicking on concrete thumbnail its large version/image opens up. This is actually not possible as MOUSE_CLICK fires everytime user drags whole thumbnail bar so large image opens up everytime.
You need to add a flag that specifies if you're in drag mode or not. If the user holds down for a certain amount of time (e.g. 300 msec), then set the flag and subsequently ignore the end MOUSE_CLICK
event. Note that we use a 1 msec timoute in the MOUSE_UP
handler to let the events finish before the flag is reset. Note also that you don't really need the click handler; you can call a pseudo-click-handler in your MOUSE_UP
handler if dragInProgress==false
.
private var dragTime:int = 300;
private var dragInProgress:Boolean = false;
private var dragInProgressInt:int;
function handleMouseDown(event:MouseEvent):void
{
dragInProgressInt = setTimeout(function():void
{
dragInProgress = true;
}, dragTime);
// Start drag, etc.
}
function handleMouseUp(event:MouseEvent):void
{
clearTimeout(dragInProgressInt);
setTimeout(function():void
{
dragInProgress = false;
}, 1);
// End drag, etc.
}
function handleMouseClick(event:MouseEvent):void
{
if (!dragInProgress)
{
// Handle the real click
}
}
The logical next step would be to wait e.g. 300 msecs before even starting the drag in the first place; this would avoid unnecessary starting/stopping of the drag operation when all the users wants is to click.
Edit: Corrected error in references to timeout name.
精彩评论