Create a gist now

Instantly share code, notes, and snippets.

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);
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment