Reputation: 2207
As my plugin does not use the selector call(not sure how this is called) I wanted to remove this.
// my plugin wrapper
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(root.jQuery);
}
}(this, function ($) {
//"use strict"; // jshint ;_;
var pluginName = 'myCustomPlugin';
function Plugin(element, options) {
this.obj = $(element);
this.o = $.extend({}, $.fn[pluginName].defaults, options);
this.init();
};
Plugin.prototype = {
init: function () {
},
show: function (text) {
alert(text);
},
destroy: function () {
this.obj.removeData(pluginName);
}
};
$.fn[pluginName] = function (option, param) {
return this.each(function () {
var $this = $(this);
var data = $this.data(pluginName);
var options = typeof option == 'object' && option;
if (!data) {
$this.data(pluginName, (data = new Plugin(this, options)))
}
if (typeof option == 'string') {
data[option](param);
}
});
};
$.fn[pluginName].defaults = {
option1: '',
option2: ''
};
}));
Currently I instantiate the plugin like this:
$('body').myCustomPlugin();
$('body').myCustomPlugin('show', 'Hello world');
I would like to change this to use this format:
$.myCustomPlugin();
$.myCustomPlugin('show', 'Hello world');
Upvotes: 0
Views: 259
Reputation: 2865
Try this out:
$.extend({
yourPluginName: function (param1, param2) {
// constructor function here
}
});
Upvotes: 0
Reputation: 7169
Add some like this
$[pluginName] = function() {
var $body = $(document.body);
$body[pluginName].apply($body, arguments);
}
to the end of wrapper. And you'll get
// my plugin wrapper
;(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(root.jQuery);
}
}(this, function ($) {
//"use strict"; // jshint ;_;
var pluginName = 'myCustomPlugin';
function Plugin(element, options) {
this.obj = $(element);
this.o = $.extend({}, $.fn[pluginName].defaults, options);
this.init();
};
Plugin.prototype = {
init: function () {
},
show: function (text) {
alert(text);
},
destroy: function () {
this.obj.removeData(pluginName);
}
};
$.fn[pluginName] = function (option, param) {
return this.each(function () {
var $this = $(this);
var data = $this.data(pluginName);
var options = typeof option == 'object' && option;
if (!data) {
$this.data(pluginName, (data = new Plugin(this, options)))
}
if (typeof option == 'string') {
data[option](param);
}
});
};
$.fn[pluginName].defaults = {
option1: '',
option2: ''
};
// Call directly from jQuery on 'body'
$[pluginName] = function() {
var $body = $(document.body);
$body[pluginName].apply($body, arguments);
}
}));
Upvotes: 1