We now want to allow the game to be dropped into the canvas that is labeled "basket". This is going to be done using the dragEnter event on the canvas. Which will fire when the item being dragged enters the canvas area. This function is simply going to add the canvas to the list of acceptable drop areas by adding itself using the function acceptDragDrop on the DropManager class.
private function dragAccept(event:DragEvent):void
{
var dropTarget:Canvas = event.currentTarget as Canvas;
DragManager.acceptDragDrop(dropTarget);
}
Once an item is dropped onto the canvas we probably want to do something. This is accomplished using the dragDrop event on the canvas. Once the drop happens we get the image from the data source that we passed along with the drag action and second we add the game to our shopping cart. This is done using the helper function addToCart which check to see if the game is in the cart and if so it increase the quantity and otherwise adds the game to the cart. I did however create a Game class (included in the source) to hold the name of the game and the number in the cart - done for data binding reasons. Both of the functions follow.
private function dragDrop(event:DragEvent):void
{
var img:Image =
event.dragSource.dataForFormat('img') as Image;
addToCart(img);
}
private function addToCart(img:Image):void
{
for(var i:int = 0; i <cartContents.length; i++)
{
if(cartContents[i].name == img.name)
{
cartContents[i].num++;
return;
}
}
cartContents.addItem(new Game(img.name, 1));
}
That takes care of drag and drop in Flex. Yes, it's that easy to do simple drag and drop and also very easy to expand to complex situations using the same techniques. I also need to give props to Belia0166 over at deviantArt for creating the icons that I used in the application. If anyone has any questions feel free to leave a comment. Also don't forget about the Drag and Drop Source Code.
Many thanks to the guys over at ParanoidFerret for another fantastic Flex tutorial!
Previous 1 2 3 Print