Skip to content

Instantly share code, notes, and snippets.

@andycole
Last active August 29, 2015 14:13
Show Gist options
  • Save andycole/325dd3970bec3fc27825 to your computer and use it in GitHub Desktop.
Save andycole/325dd3970bec3fc27825 to your computer and use it in GitHub Desktop.
AMD jQuery Plugin Template
// MYPLUGIN CLASS DEFINITION
// ==========================
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(window.jQuery);
}
}(function ($) {
var MyPlugin = function (element, options) {
'use strict';
var myplugin = this;
this.$element = $(element);
this.options = $.extend({}, MyPlugin.defaults, options);
this.$element.on('mouseover', function () {myplugin.publicMethod();});
};
MyPlugin.defaults = {
someVar: 50,
nextVar: 'Some text'
};
MyPlugin.prototype = {
myAttribute: 'value',
_privateMethod: function () {
//Does something private.
},
publicMethod: function () {
//Does something public.
}
};
$.fn.myplugin = function (option) {
var args = [].splice.call(arguments, 1);
return this.each(function () {
var $this = $(this),
data = $this.data('myplugin'),
options = typeof option === 'object' && option;
if (!data) {
$this.data('myplugin', (data = new MyPlugin(this, options)));
} else if (typeof option === 'string') {
data[option].apply(data, args);
}
});
};
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment