Ember Drag and Drop demo
Answer to: http://stackoverflow.com/questions/10762484/ember-js-html5-drag-and-drop-shopping-cart-demo
HTML
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-latest.js"></script>
<script type="text/x-handlebars" >
<b>Available Objects</b><br /><br />
{{#each App.objectsController.objectsNotInCart}}
{{#view App.ObjectView contentBinding="this"}}
{{view.content.name}}<br />
{{/view}}
{{/each}}
<br /><br /><br /><br />
{{#view App.ObjectDropTarget dragContextBinding="App.objectsController.currentDragItem"}}
{{#each App.cartController}}
{{#view App.ObjectView contentBinding="this" class="single"}}
{{view.content.name}}<a href="#" {{action removeObject this}}>x</a>
{{/view}}
{{/each}}
{{/view}}
</script>
CSS
.dropTarget {
width: 200px;
min-height:50px;
color: #000;
border: 2px dotted #000;
border-radius: 4px;
}
.cart-add {
background-color: #55A122;
}
.cart-remove {
background-color: #A12255;
}
.single {
width:50%;
float:left;
}
JavaScript
App = Em.Application.create({});
DragNDrop = Em.Namespace.create();
DragNDrop.cancel = function(event) {
event.preventDefault();
return false;
};
DragNDrop.Draggable = Em.Mixin.create({
attributeBindings: 'draggable',
draggable: 'true',
dragStart: function(event) {
var dataTransfer = event.originalEvent.dataTransfer;
dataTransfer.setData('Text', this.get('elementId'));
}
});
DragNDrop.Droppable = Em.Mixin.create({
dragEnter: DragNDrop.cancel,
dragOver: DragNDrop.cancel,
drop: function(event) {
event.preventDefault();
return false;
}
});
App.Object = Em.Object.extend({
name: null,
isAdded: null
});
App.ObjectView = Em.View.extend(DragNDrop.Draggable, {
tagName: 'div',
// .setDragImage (in #dragStart) requires an HTML element as the first argument
// so you must tell Ember to create the view and it's element and then get the
// HTML representation of that element.
dragStart: function(event) {
this._super(event);
// Let the controller know this view is dragging
this.setPath('content.isDragging', true);
// Set the drag image and location relative to the mouse/touch event
},
dragEnd: function(event) {
// Let the controller know this view is done dragging
this.setPath('content.isDragging', false);
},
removeObject: function(event) {
this.setPath('content.isAdded', false)
}
});
App.ObjectDropTarget = Em.View.extend(DragNDrop.Droppable, {
tagName: 'div',
classNames: ['dropTarget'],
classNameBindings: ['cartAction'],
// This will determine which class (if any) you should add to
// the view when you are in the process of dragging an item.
drop: function(event) {
var viewId = event.originalEvent.dataTransfer.getData('Text'),
view = Em.View.views[viewId];
// Set view properties
// Must be...