desandro / draggabilly

:point_down: Make that shiz draggable
https://draggabilly.desandro.com
MIT License
3.86k stars 386 forks source link

Support for event delegation #79

Closed rj33 closed 8 years ago

rj33 commented 9 years ago

Does the code the currently support event delegation (or plan to do so in the future?). I have a large number of objects that need to be draggable, and being able to have a single instance handle all of them via event delegation would be ideal.

desandro commented 9 years ago

You can do event delegation if you are using jQuery. See CodePen: http://codepen.io/desandro/pen/VYEpmK

$('.draggable').draggabilly();
// listen to parent element for delegated event
$('body').on( 'dragStart', function() {
  console.log('dragStart');
});

As for vanilla JS: sorry, no. Draggabilly uses a base EventEmitter class that does not have the browser DOM-tree event delegation that jQuery events provide. But, you can use generic event listeners for multiple instances. See CodePen: http://codepen.io/desandro/pen/NPOpdM

// get all draggie elements
var draggableElems = document.querySelectorAll('.draggable');
// array of Draggabillies
var draggies = []
// init Draggabillies
for ( var i=0, len = draggableElems.length; i < len; i++ ) {
  var draggableElem = draggableElems[i];
  var draggie = new Draggabilly( draggableElem, {
    // options...
  });
  draggie.on( 'dragStart', onDragStart );
  draggies.push( draggie );
}

function onDragStart() {
  // within event listener `this` refers to Draggabilly instance
  console.log( 'dragStart', this.element );
}
rj33 commented 9 years ago

Thanks for your very detailed reply! Unfortunately I'm trying to avoid JQuery, and have a use case that can have 3200+ draggable objects so I'm trying to avoid the instance per draggable approach, although I should probably benchmark it before ruling it out. Thanks again!