Last active
August 12, 2017 13:20
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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