Monday, August 13, 2012

Toggling Drag Drop in Canvas

Well this one was a bit peculiar. What I had to do was to toggle the drag drop in a Canvas based on some events. Sounds pretty simple. All that I had to do is add and remove event listeners for drag drop done. But, what is peculiar is that, it didn't work.

Lets say my code was something like this.

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" 
   dragEnter="doDragEnter(event)" dragExit="{doDragExit(event)}" >

public function doDragEnter(event:DragEvent):void
{
   //Some code...
}

public function doDragExit(event:DragEvent):void
{
   //Some code...
}

public function toggleDragDrop(allow:Boolean):void
{
   if(allow)
   {
      if(!this.hasEventListener(DragEvent.DRAG_ENTER))
         this.addEventListener(DragEvent.DRAG_ENTER, doDragEnter);

      if(!this.hasEventListener(DragEvent.DRAG_EXIT))
         this.addEventListener(DragEvent.DRAG_EXIT, doDragExit);
   }
   else
   {
      if(this.hasEventListener(DragEvent.DRAG_ENTER))
         this.removeEventListener(DragEvent.DRAG_ENTER, doDragEnter);

      if(this.hasEventListener(DragEvent.DRAG_EXIT))
         this.removeEventListener(DragEvent.DRAG_EXIT, doDragExit);
   }
}

</mx:Canvas>

But that doesn't work. The event listeners remain. I have not yet figured out the reason for this, but definitely a workaround. SO, what you can do is something like this.

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" 
   dragEnter="doDragEnter(event)" dragExit="{doDragExit(event)}" >

public var enableDragDrop:Boolean = true;
public function doDragEnter(event:DragEvent):void
{
   if(!enableDragDrop)
   {
      event.stopImmediatePropagation();
      return;
   }
   //Some code...
}

public function doDragExit(event:DragEvent):void
{
   if(!enableDragDrop)
   {
      event.stopImmediatePropagation();
      return;
   }
   //Some code...
}

</mx:Canvas>

Worked like a charm. Hope this helps someone for a quick solution as of now.

No comments :