I have many drag and drop objects on the stage, and the default code snippet adds a new event listener and function to the stage for each object:
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void { instance_1.stopDrag(); }
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_1);
function fl_ReleaseToDrop_1(event:MouseEvent):void { instance_2.stopDrag(); }
....
Would it be better or worse to put them all into one listener?
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void {
instance_1.stopDrag();
instance_2.stopDrag();
....
}
One function call is surely faster than multiple function calls. However, the difference here is going to be negligible.
From a code readability stand-point, I would say the single function call you've shown is better.
Generally, the way I like to do drag-and-drop is to add the mouseUp
handler when I start the drag, and remove it immediately when dragging is completed. For example:
instance1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
function mouseDown(e:MouseEvent):void {
Sprite(e.currentTarget).startDrag();
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
}
function mouseUp(e:MouseEvent):void {
stopDrag();
stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUp);
}
For a Flash timeline easy and efficient solution you simply keep reference to your object and that's about it:
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUp);
instance1.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance2.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
instance3.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
var draggedObject:Sprite;
function mouseDown(e:MouseEvent):void
{
draggedObject = e.currentTarget as Sprite;
if(draggedObject)
{
draggedObject.startDrag();
}
}
function mouseUp(e:MouseEvent):void
{
if(draggedObject)
{
draggedObject.stopDrag();
draggedObject = null;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.