JSFiddle - React, Tailwind, and code Playground
HTML
<!--
This sample demonstrates the problems with a very common jQuery custom plugin technique.
In this demonstration, we are initializing 5 custom plugins, one to each of the divs in the DOM...
At least, that's what we think we are doing.
In reality, we are actually just initializing a single custom plugin and passing in the divs as the
scope.
Read the comments in the JavaScript pane for the explanation.
View this fiddle for a technique that solves these problems: http://jsfiddle.net/Aq7Y4
Authored by Kevin Jurkowski, 04/09/14
-->
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
CSS
div {
background: red;
height: 40px;
margin-top: 10px;
width: 40px;
}
JavaScript
(function($) {
var methods = {
init: function(options) {
// Here, as you likely don't realize, `this` is the jQuery selector, not the plugin.
//
// This means that we are actually setting `_defaults` and `_options` on the jQuery selector,
// not within the plugin itself, as you would expect.
//
// This also means that only one `_defaults` and one `_options` object exists, not one
// for each div in the selector (for a total of 5 each, since there are 5 divs),
// as you would expect.
//
this._defaults = {
randomizer: Math.random() * 100
};
this._options = $.extend(true, {}, this._defaults, options);
// Open up the console to see that `_defaults` and `_options` are attached to the selector.
console.log(this);
},
options: function() {
// Since this is returning the options object stored on the jQuery selector,
// calling this method through a new jQuery selector will not return anything
// without init being called first.
//
// For example:
//
// $('div').customPlugin();
// $('div').customPlugin('options'); // will return undefined
//
// var divs = $('div').customPlugin();
// divs.customPlugin('options'); // will return the single options object
//
// This means you'll need to cache your selector somewhere, or else you'll
// lose your options forever!
//
return this._options;
},
move: function() {
// Here we are setting the CSS to all 5 divs on the page in one call,
// not setting the CSS to one individual div, as you would expect.
$(this).css('margin-left',...