Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm rodneyrehm/gist:6464641
Last active Sep 23, 2019

Embed
What would you like to do?
Rachel Nabors: touch and click
// https://coderwall.com/p/yzlqpq
(function($){
function touch(event) {
event.preventDefault();
var runFunc = $(this).data('activateRunFunc');
runFunc && runFunc();
}
function click(event) {
event.preventDefault();
event.stopImmediatePropagation();
var runFunc = $(this).data('activateRunFunc');
runFunc && runFunc();
}
$.fn.activate = function(runFunc) {
return $(this).data('activateRunFunc', runFunc).on({
touchend: touch,
click: click
});
};
})(jQuery);
@rodneyrehm

This comment has been minimized.

Copy link
Owner Author

rodneyrehm commented Sep 7, 2013

I kept Rachel's example intact but changed a couple of things around. Here's a brief list:

  1. Wrap your stuff in an IIFE to make sure you're not bleeding variables to the global scope. This also allows capturing a specific instance of jQuery in case multiple versions were loaded or the $.noConflict() were to be invoked later on.
  2. never declare functions within functions. They get copied in memory and simply use more of your precious RAM than they need to.
  3. Know thy jQuery API - .on() accepts maps for a more concise registration
  4. don't repeat selectors, even if it's $(this)

jQuery knows Special Events, something they redefined as Event Extensions. If you are to process more complex event handling, this is an infrastructure you want to look into. It allows you to handle all that "touch or click" business behind the scenes and use $(selector).on('your-custom-event', runFunc) - making stuff simpler and easier to maintain in the long run.

@andrenellin

This comment has been minimized.

Copy link

andrenellin commented Sep 23, 2019

Are you willing to explain what's happening here? Where do I place the functionality that I need once the event is triggered?

@rodneyrehm

This comment has been minimized.

Copy link
Owner Author

rodneyrehm commented Sep 23, 2019

$('your-selector').activate(function (event) {
  console.log('event was dispatched', event)
})

does that help?

@andrenellin

This comment has been minimized.

Copy link

andrenellin commented Sep 23, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.