Draggable.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. var Param = (function () {
  2. function Param(target, e) {
  3. this.target = target;
  4. this.topTarget = e && e.topTarget;
  5. }
  6. return Param;
  7. }());
  8. var Draggable = (function () {
  9. function Draggable(handler) {
  10. this.handler = handler;
  11. handler.on('mousedown', this._dragStart, this);
  12. handler.on('mousemove', this._drag, this);
  13. handler.on('mouseup', this._dragEnd, this);
  14. }
  15. Draggable.prototype._dragStart = function (e) {
  16. var draggingTarget = e.target;
  17. while (draggingTarget && !draggingTarget.draggable) {
  18. draggingTarget = draggingTarget.parent || draggingTarget.__hostTarget;
  19. }
  20. if (draggingTarget) {
  21. this._draggingTarget = draggingTarget;
  22. draggingTarget.dragging = true;
  23. this._x = e.offsetX;
  24. this._y = e.offsetY;
  25. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragstart', e.event);
  26. }
  27. };
  28. Draggable.prototype._drag = function (e) {
  29. var draggingTarget = this._draggingTarget;
  30. if (draggingTarget) {
  31. var x = e.offsetX;
  32. var y = e.offsetY;
  33. var dx = x - this._x;
  34. var dy = y - this._y;
  35. this._x = x;
  36. this._y = y;
  37. draggingTarget.drift(dx, dy, e);
  38. this.handler.dispatchToElement(new Param(draggingTarget, e), 'drag', e.event);
  39. var dropTarget = this.handler.findHover(x, y, draggingTarget).target;
  40. var lastDropTarget = this._dropTarget;
  41. this._dropTarget = dropTarget;
  42. if (draggingTarget !== dropTarget) {
  43. if (lastDropTarget && dropTarget !== lastDropTarget) {
  44. this.handler.dispatchToElement(new Param(lastDropTarget, e), 'dragleave', e.event);
  45. }
  46. if (dropTarget && dropTarget !== lastDropTarget) {
  47. this.handler.dispatchToElement(new Param(dropTarget, e), 'dragenter', e.event);
  48. }
  49. }
  50. }
  51. };
  52. Draggable.prototype._dragEnd = function (e) {
  53. var draggingTarget = this._draggingTarget;
  54. if (draggingTarget) {
  55. draggingTarget.dragging = false;
  56. }
  57. this.handler.dispatchToElement(new Param(draggingTarget, e), 'dragend', e.event);
  58. if (this._dropTarget) {
  59. this.handler.dispatchToElement(new Param(this._dropTarget, e), 'drop', e.event);
  60. }
  61. this._draggingTarget = null;
  62. this._dropTarget = null;
  63. };
  64. return Draggable;
  65. }());
  66. export default Draggable;