Skip to content

Instantly share code, notes, and snippets.

@seriema
Last active August 12, 2017 13:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seriema/5915653 to your computer and use it in GitHub Desktop.
Save seriema/5915653 to your computer and use it in GitHub Desktop.
A really simple widget pattern for jQuery. Personally I would recommend using Angular, Ember, React, or something else that already has a good system for this, but sometimes you don't have a choice and this simple pattern has helped me many times. You can wrap it like this: https://gist.github.com/seriema/4b3a818ce85b6ab03ddd
// This is the basic principle of a minimalistic jQuery based widget system.
// Every widget has one root element, with a unique classname prefix. Here I used "w-".
//
// First, select all those widgets on the page with $('.w-...').
// Second, iterate over all of them and work with them in a local scope.
$(function() {
$('.w-my-widget').each(function() {
// Grab the elements you need.
var $root = $(this);
var $child = $root.find('.child'); // Always use .find() from $root or a child of $root, to avoid global selectors and potential bugs with one widget affecting another.
var $button = $root('.button');
var clickCounter = 0;
// Declare any functions you'll use.
var myClickHandler = function () {
clickCounter++;
$child.text('The button got clicked ' + clickCounter + ' times!');
}
// Attach any events you'll need.
$button.on('click', myClickHandler);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment