;(function ($, window, document, undefined) {
// Create the defaults once
var pluginName = "myplugin",
defaults = {
settingA: 'someValue',
settingB: 'someValue'
};
// The actual plugin constructor
function Plugin(params) {
params.options = $.extend({}, defaults, params.options);
this.params = params;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
this.cacheElements();
this.bindEvents();
},
cacheElements: function () { //cache elements
this.$el = $('div.doSomething');
},
bindEvents: function () {
// To make the main plugin available in myFunction I need to pass it in the data
this.$el.on('click', {base: this}, this.myFunction);
},
myFunction: function (event) {
console.log(this); //this now refers to $el
console.log(event.data.base); //This is a reference to my main plugin
}
};
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function (params) {
return this.each(function () {
if (!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName,
new Plugin(params));
}
});
};
})(jQuery, window, document);
$(function () {
$('div.doSomething').myplugin({
settingA: 'someOtherValue'
});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.