zit*_*tix 6 javascript jquery jquery-plugins
如何向我的自定义jQuery插件添加公共方法,该插件基于jquery-boilerplate中的这种模式:https: //github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.extend-skeleton. JS
我需要使用我的插件并调用这样的公共方法:
jQuery('.element').pluginName();
//And now assuming that plugin has a public method `examplePublicMethod`,
//I want to call it like this:
var instance = jQuery('#element').data('pluginName');
instance.examplePublicMethod();
Run Code Online (Sandbox Code Playgroud)
当我从链接中使用这个模式时,它是否可能?这是这种模式的代码示例:
;(function($){
$.fn.extend({
pluginName: function( options ) {
this.defaultOptions = {};
var settings = $.extend({}, this.defaultOptions, options);
return this.each(function() {
var $this = $(this);
//And here is the main code of the plugin
//...
//And I'm not sure how to add here a public method
//that will be accessible from outside the plugin
});
}
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
有多种方法可以做到这一点,但我喜欢的是这样的:
$.fn.extend({
pluginName: function( options ) {
this.defaultOptions = {};
var settings = $.extend({}, this.defaultOptions, options);
return this.each(function() {
var $this = $(this);
//Create a new Object in the data.
$this.data('pluginName', new pluginMethods($this)) //pluginMethod are define below
});
}
});
function pluginMethods($el){
//Keep reference to the jQuery element
this.$el = $el;
//You can define all variable shared between functions here with the keyword `this`
}
$.extend(pluginMethods.prototype, {
//Here all you methods
redFont : function(){
//Simply changing the font color
this.$el.css('color', 'red')
}
})
$('#el').pluginName();
//Public method:
var instance = jQuery('#el').data('pluginName');
instance.redFont();
Run Code Online (Sandbox Code Playgroud)
缺点是每个人都可以访问pluginMethods.但你可以通过在插件声明的相同闭包中移动它来解决这个问题:
(function($){
$.fn.extend({
pluginName: function( options ) {
this.defaultOptions = {};
var settings = $.extend({}, this.defaultOptions, options);
return this.each(function() {
var $this = $(this);
$this.data('pluginName', new pluginMethods($this))
});
}
});
function pluginMethods($el){
//Keep reference to the jQuery element
this.$el = $el;
}
$.extend(pluginMethods.prototype, {
//Here all you methods
redFont : function(){
this.$el.css('color', 'red')
}
})
})(jQuery);
Run Code Online (Sandbox Code Playgroud)