由于我的插件不使用选择器调用(不确定如何调用它),我想删除它。
// 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: ''
};
}));
目前我像这样实例化插件:
$('body').myCustomPlugin();
$('body').myCustomPlugin('show', 'Hello world');
我想将此更改为使用此格式:
$.myCustomPlugin();
$.myCustomPlugin('show', 'Hello world');
答案 0 :(得分:1)
添加一些这样的
$[pluginName] = function() {
var $body = $(document.body);
$body[pluginName].apply($body, arguments);
}
到包装器的末尾。你会得到
// 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);
}
}));
答案 1 :(得分:0)
试试这个:
$.extend({
yourPluginName: function (param1, param2) {
// constructor function here
}
});