Skip to content

Instantly share code, notes, and snippets.

@thomasyip
Last active December 21, 2015 15:28
Show Gist options
  • Save thomasyip/6326560 to your computer and use it in GitHub Desktop.
Save thomasyip/6326560 to your computer and use it in GitHub Desktop.
Skeleton of jQuery plugin
;(function($, undefined) {
var PLUGIN_NAME = 'plugin';
var DEFAULT_OPTIONS = {
optionA: true,
optionB: false,
'callbackC': function() {
}
};
function plugin(options) {
var element = this;
var $element = $(element);
var instance = {};
var options = $.extend({}, DEFAULT_OPTIONS, options);
// main action here:
// ...
instance = $.extend(instance, {
// public methods:
});
return instance;
}
$.fn[PLUGIN_NAME] = function(method, arg) {
var args = arguments,
results = undefined, $selector;
$selector = $(this).each(function() {
var $this = $(this),
instance;
instance = $this.data(PLUGIN_NAME);
if (instance === undefined) {
if (typeof method !== 'string') {
$this.data(PLUGIN_NAME);
instance = plugin.call(this, method);
$this.data(PLUGIN_NAME, instance);
} else {
$.error('Function "' + method + '" is called before "' + PLUGIN_NAME + '" is initialized.');
}
} else {
if (method in instance && $.isFunction(instance[method])) {
results = instance[method].apply(instance, Array.prototype.slice.call(args, 1));
} else {
$.error('Function "' + method + '" is not found in "' + PLUGIN_NAME + '".');
}
}
});
return results !== undefined? results: $selector;
};
}($));
@thomasyip
Copy link
Author

Optional css file loading:

    var src = $("head script").last().attr("src") || '';
    var scriptpath = src.split('?')[0].split('/').slice(0, -1).join('/')+'/';
    var csspath = scriptpath + PLUGIN_NAME;
    var link = $('<link href="' + csspath + '" rel="stylesheet">');
    $('head').append($(link));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment