7476

Is it possible to use a jquery function such as delegate to listen to jquery ui events?

Question:

i want to know if its possible to use a function like .delegate(), .on() or any in a way that it will listen to jquery UI events such as draggable. I have the following:

HTML:

<div id="wrapper"></div>​

javaScript:

$(function(){ var addMe='<div id="draggable" class="ui-widget-content">

Drag me around

</div>' $( "#wrapper" ).delegate('#draggable','draggable',function(){ console.log('its something!'); }); //$(".draggable").draggable(); $("#wrapper").append(addMe) })

The element that is going to be draggable is dynamically added so that is way i want to use delegate or on.

Also note that i'm aware of <a href="https://stackoverflow.com/questions/9857143/how-do-i-add-draggable-list-items-from-the-result-of-a-ajax-get" rel="nofollow">How do I add draggable List Items from the result of a .ajax GET?</a> and even that solution can work for me i have to modify the .post() function which is not what i'm asking.

Here is the <a href="http://jsfiddle.net/yTBkk/13/" rel="nofollow">problem</a>

Answer1:

This is a very common question....how to use delegation to invoke plugins , and there is no holy grail like on(). In the case of almost all jQueryUI widgets there is far more involved than simply binding events, the html and element data needs to be connstructed.

ALthough there is no delegation method, you can use $.ajaxComplete() as a global handler to initialize plugins , if it suits your application. It can be bound to any element, which allows using this within handler

$('#content').ajaxComplete(function(e, xhr, settings){ /* url conditional*/ if (settings.url == 'getMoreDraggables.php') { $(this).find('.newDraggable').removeClass('newDraggable').draggable() } /* element conditional */ if( $(this).find('.newDraggable').length){ /* run code for true*/ } });

Can also add conditionals based on xhr object

Answer2:

It is not possible to use event delegation to automatically create jQuery UI widgets. Your best bet is to explicitly destroy and recreate.

$('.draggable').draggable('destroy'); $('.draggable').draggable();

See <a href="http://jsfiddle.net/hTCLB/" rel="nofollow">http://jsfiddle.net/hTCLB/</a>

Answer3:

Can't you just execute a function calling the .draggable() in the callback of your Ajax requests?

Otherwise, you can observe the wrapper with a <a href="http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/" rel="nofollow">DOM Mutation Observer</a> and use an anonymous function to call the .draggable() when new elements are appended. It's very similar to event delegation as you asked, but I'm not sure how good that is for older versions of IE.

Example code with Observer:

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver; var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation.type === 'childList' && mutation.addedNodes.length) { $("#draggable").draggable(); } }); }); observer.observe($('#wrapper')[0], { attributes: false, childList: true, characterData: true });

<a href="http://jsfiddle.net/4xcRJ/" rel="nofollow"><strong>JSFiddle with DOM Mutation Observer</strong></a>

<a href="http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/" rel="nofollow">Reference</a>

Also, if you can't use the Ajax call's callback for this, odds are there is a logic/design flaw in your application. I'd suggest taking a look on that before shoving down hacks as the DOM Mutation Observer.

Recommend

  • Value get lost in python generator/coroutine
  • Which version of Grails support JDK 8?
  • How to make the cancel button in alert cancel the action?
  • Creating two objects in Rails 4 controller with strong_params
  • Exception using DateTime in a parameterized OleDbCommand
  • yocto: how to install command locale & localedef?
  • Add completion handler to presentViewControllerAsSheet(NSViewController)?
  • Ignore mapView:didSelectAnnotationView when long press is occuring
  • ERROR_USER_UNAUTHORIZED when deploy to IIS 7.5 when using IIS manager user
  • Ordering list with jQuery drag and drop
  • Jquery javascript: have a filtering list(works), need help keeping all LI's visible when there&
  • JQuery Mobile 1.4 How to Disable Hover Effect on Mobile Devices
  • Is it good practice to put Edge Side Includes into my templates?
  • Nested jQuery tabs
  • k-ary Trees in Java
  • Starting Android AVD crashes with java.awt.HeadlessException
  • How to get value of the slider, when touchend or mouseup events are used?
  • MAVEN : Run Multiple Maven Project using Maven Test
  • Save image as is in photo album using swift
  • Reading space separated values file in c++ error
  • Changing references to deprecated methods C++
  • TFS - how do I sum child task hours to parent
  • jquery validation - waiting for remote check to complete
  • How to pass EC named curve list used by SSL_CTX?
  • How to copy styled text in JTextPane
  • How to override value that appears in a dropdown in the rails_admin gem
  • How to autopopulate a field in SugarCRM form
  • WPF ICommand CanExecute(): RaiseCanExecuteChanged() or automatic handling via DispatchTimer?
  • OOP Javascript - Is “get property” method necessary?
  • JQuery Internet Explorer and ajaxstop
  • Use of this Javascript
  • How do I change content of ComboFieldEditor?
  • Master page gives error
  • Redux, normalised entities and lodash merge
  • jQuery tmpl and DataLink beta
  • Comma separated Values
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • JaxB to read class hierarchy
  • How to load view controller without button in storyboard?