简体   繁体   中英

Startdrag is not a function

this.addEventListener(MouseEvent.MOUSE_DOWN,function(e:MouseEvent){this.startDrag(false,null);});

Hi I was wondering why the above doesnt work? Im trying to drag a sprite around screen.

create a sprite on stage, add instance name box, add code to frame one:

box.addEventListener(MouseEvent.MOUSE_DOWN, startMove);

function startMove(evt:MouseEvent):void {
   box.startDrag();
}

box.addEventListener(MouseEvent.MOUSE_UP, stopMove);

function stopMove(e:MouseEvent):void {
   box.stopDrag();
}

I think your example doesn't work because of the scope of "this" in the event listener handler.

If you remove this. ; it will work. It's a scope issue since you use an anonymous function. You could use the currentTarget of the event, this allows you to make other boxes draggable too, if you add the same listeners.

Note: It is hard to remove an anonymous function as event listener and could cause memory leaks, so the best way is to use a reference to a named function:

box.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseEvent);
box.addEventListener(MouseEvent.MOUSE_UP, handleMouseEvent);

function handleMouseEvent(event:MouseEvent):void 
{
    switch(event.type)
    {
       case MouseEvent.MOUSE_DOWN:
       {
         DisplayObject(event.currentTarget).startDrag();
         break;
       }
       case MouseEvent.MOUSE_UP:
       {
         DisplayObject(event.currentTarget).stopDrag();
         break;
       }
   }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM