Saturday, July 14, 2007

Dragging and dropping from a tree in Flex

This might be common knowledge to some but it took me a bit to figure this out. Suppose you have a tree of items such as a hierarchical list of folders and you want to enable the user to drag an item out of the tree onto a trashcan.

Here is a snippet of the code:

<mx:Tree x="10" top="10" bottom="75" width="200" id="tree"
labelField="name" dragEnabled="true"/>

<local:TrashCan id="trash" dragdrop="deleteItem(event)"


private function doDragEnter(event:DragEvent):void {
var dragInitiator:TrashCan=TrashCan(event.currentTarget);

private function deleteItem(event:DragEvent) : void {
//do the actual delete here.

When you run this code everything works except you get an error. The problem was that the default behavior when dragging from a tree expects that you are dropping the item into a tree, either the same tree or a different one. Since my TrashCan was not a subclass of Tree the error was being thrown.

The simple solution is to tell the tree to skip the default behavior. The way you do it is to add dragComplete="event.preventDefault()" to the Tree.


holla2040 said...

Closing a node after you've deleted all its children (through drag to trash) throws a series of null child errors. Do you have a solution for this? Thanks.

DecoX said...

WTF??? Your code is nothing!!! Where is the dropping code from a tree??? I cant believe it I found this **** from google