简体   繁体   中英

Trigger custom event in jQuery for use with live()

I have written a series of plugins for jQuery which essentially act as events for mobile browsers. You can see them here > http://ben-major.co.uk/2011/11/jquery-mobile-events/ .

Currently, they are called by $(ele).tap(handler) and so forth, but I would like to add in functionality to also fire custom events, so that the functions can be harnessed using something like $(ele).on('tap', handler); .

I am using the following code right now, but this does not seem to work:

$(function() {
    $('*').tapstart(function() { $(this).trigger('tapstart'); })
          .tapend(function() { $(this).trigger('tapend'); })
          .tap(function() { $(this).trigger('tap'); })
          .doubletap(function() { $(this).trigger('doubletap'); })
          .taphold(function() { $(this).trigger('taphold'); })
          .swipedown(function() { $(this).trigger('swipedown'); })
          .swipeup(function() { $(this).trigger('swipeup'); })
          .swipeleft(function() { $(this).trigger('swipeleft'); })
          .swiperight(function() { $(this).trigger('swiperight'); });
});

Here's a jsFiddle to demonstrate my problem. Obviously clicking on the second div should mimic the action of the first, but since it was added to the DOM after the bindings given above were parsed, it doesn't.

I guess my question is: what's the best way to achieve what I want? Is there a way to select all elements which exist in the DOM now and in the future (if possible, I would rather not use something like livequery , or an external plugin).

In your case, I don't think jQuery will handle your custom events properly (as a custom event are not bubbled up to the document). The answer is to bind a branch of event listeners to document . and don't use jQuery in this situation for good.

jQuery's live mode almost do the same thing as I suggested, but it will try to match a the event.target with the bound selector (say '*' in your question,) which is very slow (also battery drainer for mobiles.)

If you want to interact with certain type or certain className of element, just handle it by your self, and fire desired event handlers.

an example:

function findAncestorOfType(el, type) {
  while (el && !(el instanceof type))
    el = el.parent;
  return el;
}

document.addEventListener('click', function(evt) {
  var target = findAncestorOfType(evt.target, LIElement);
  if (target) {
    // distinguish event type
    type = 'click';
    callbacks[type](target, evt);
  }
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM