jQuery draggable - what happens if it is applied twice to an element?

做~自己de王妃 提交于 2019-12-01 21:33:04

No, there won't be extra handlers bound. jQuery registers the initialized instance to the element and won't create a new instance of the same widget for the same element.

As you're worried about handlers, here's a quick check (jQuery 1.8+ and UI 1.9+):

$('div').draggable();
console.log( $._data($('div')[0], 'events') );
$('div').draggable();
console.log( $._data($('div')[0], 'events') );

Fiddle

As you can see, the attached handlers object is not altered after trying to initialize a new draggable instance on the same element.

edit: Subsequent calls with parameters won't be ignored though, rather they will extend the existing widget as shown on @Jason Sperske's answer.

Subsequent calls to .draggable() extend previous calls when attached to the same object (and not replace them as I had originally thought). See this example (extended from Fabrício Matté's) (demo)

<div>foo</div>
<script>
 $('div').draggable({
  start: function () {
    console.log("drag 1");
  }
 });
 console.log($._data($('div')[0], 'events'));
 $('div').draggable({
  stop: function () {
    console.log("drag 2");
  }
 });
 console.log($._data($('div')[0], 'events'));
</script>

In the console.log you see only these messages:

drag 1 <- on start
drag 2 <- on stop
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!