Print Shortlink

Plain vanilla drag n drop in Ext JS4

The drag and drop examples in Ext JS4 look overly complicated that one keeps wondering if drag and drop implementation is very difficult. It’s actually pretty simple.

Let’s drag a simple label into a panel as shown below.

Before DnD

After DnD

Three basic steps that you need to follow for this.
1) Define the component that can be dragged using DragZone.
2) Define the component that acts as a container where items will be dropped, using DropZone.
3) Using the data passed from the dragged item to the dropped container, you decide what you want to do.

In our example let’s configure the Label as the DragZone object and the panel as the DropZone object. The configuration of the DragZone and DropZone is done on the underlying DOM element of the label and panel. For this purpose, you will configure this in the render event of these two components.

//Label configured as DragZone
var lbl = {
	       	xtype : "label",
	       	text : "Hello DnD",
	       	id : "lbl",
	       	padding : 5,
	       	margin : 15,
		listeners : {
		       		render : function(v){
		       			lbl.dragZone = Ext.create("Ext.dd.DragZone",v.getEl(),{
		      				getDragData : function(e){
		       				   var sourceEl = e.getTarget();
			        		   var clonedSourceEl = sourceEl.cloneNode(true);
			        		   return lbl.dragData = {
			        		           ddel: clonedSourceEl,//mandatory
			        		           sourceEl: sourceEl
			        		   }
			        		}
			        	});
			        }
			   }     
};

The render event of the label configures it as the DragZone. In the getDragData function you merely clone the label element and pass it to the drop zone.
“ddel” is a mandatory element that contains the clone and other extra information is passed as data to the drop zone. The panel which is the drop zone will consume this data and react accordingly.

//Panel configured as DropZone
var pnl = {
	title : "Destination",
	padding : 20,
	height : 150,
	width : 200,
	listeners : {
		render : function(v){
		    pnl.dropZone = Ext.create("Ext.dd.DropZone",v.getEl(),{
				getTargetFromEvent: function(e) {
			            return e.getTarget();
			        },
				onNodeDrop : function(target,dd,e,data){
			            targetEl = Ext.get(target);
				    targetEl.update(data.sourceEl.innerHTML);
				    data.sourceEl.innerHTML = "";
				},
			});
		}
	}        
};

The panel is configured as the drop zone above. The onNodeDrop function gets the data that is received from the drag zone and updates the panel. The main Ext.application code is shown below.

Ext.application(
{
	launch : function(){
	    Ext.create("Ext.panel.Panel",{
			layout : "hbox",
			padding : 20,
			height : 200,
			width : 350,
			items : [
			          lbl,pnl
			        ],
			renderTo : Ext.getBody()        
		});
	}
});

Leave a Reply