Last active
January 21, 2016 19:45
-
-
Save erfanio/8ed278f6a61385a6c447 to your computer and use it in GitHub Desktop.
jquery plugin template
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
// the semi-colon before function invocation is a safety net against concatenated | |
// scripts and/or other plugins which may not be closed properly. | |
;(function ($) { | |
var privateMethod = function () { | |
// ... | |
}; | |
var Plugin = function (element, options) { | |
// `this` refers to a `Plugin` intance | |
this.element = element; | |
this.options = { | |
// default options | |
}; | |
/* | |
* Initialization | |
* | |
* | |
* `this` inside a jquery function refers to a DOM element | |
* this.element.fadeIn('normal', function(){ | |
* `this` keyword is a DOM element | |
* }); | |
*/ | |
this.init(options); | |
}; | |
Plugin.prototype = { | |
// initialize options | |
init: function (options) { | |
// Merge new options with old options | |
$.extend(this.options, options); | |
/* | |
* Update plugin for options | |
*/ | |
}, | |
publicMethod: function () { | |
// ... | |
} | |
}; | |
/* | |
* Plugin wrapper, preventing against multiple instantiations and | |
* return plugin instance. | |
*/ | |
$.fn.pluginName = function (options) { | |
// `this` is a jquery object | |
// $(this) == $($('selector')) | |
var plugin = this.data('datakey'); | |
// has plugin instantiated ? | |
if (plugin instanceof Plugin) { | |
// if have options arguments, call plugin.init() again | |
if (typeof options !== 'undefined') { | |
plugin.init(options); | |
} | |
} else { | |
// `new` calls Plugin as a constructor | |
plugin = new Plugin(this, options); | |
this.data('datakey', plugin); | |
} | |
return plugin; | |
}; | |
}(jQuery)); | |
/* | |
If you need independent Plugin instance per element | |
$('selector').each(function () { | |
$(this).pluginName(); | |
}); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment