Skip to content

Instantly share code, notes, and snippets.

@rodneyrehm
Last active September 18, 2020 02:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodneyrehm/6464641 to your computer and use it in GitHub Desktop.
Save rodneyrehm/6464641 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

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

@rodneyrehm
Copy link
Author

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

does that help?

@andrenellin
Copy link

andrenellin commented Sep 23, 2019 via email

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