如何将公共(public)方法添加到我的自定义 jQuery 插件中,该插件基于 jquery-boilerplate 中的这种模式: https://github.com/jquery-boilerplate/jquery-patterns/blob/master/patterns/jquery.extend-skeleton.js
我需要使用我的插件并像这样调用公共(public)方法:
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();
当我使用链接中的这种模式时,是否完全可行?这是此模式的代码示例:
;(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);
最佳答案
有多种方法可以做到这一点,但我更喜欢这样的方法:
$.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();
缺点是每个人都可以访问 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);
关于javascript - 如何根据此 jQuery 插件模式将公共(public)方法添加到 jQuery 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24187783/