以下插件结构利用
jQuery-data()
-方法 来提供对内部插件方法/设置的公共接口(同时保留 jQuery 的链式调用):
(function($, window, undefined) {
const defaults = {
elementId : null,
shape : "square",
color : "aqua",
borderWidth : "10px",
borderColor : "DarkGray"
};
$.fn.myPlugin = function(options) {
var settings = $.extend({}, defaults, options);
var setBorder = function(color, width) {
settings.borderColor = color;
settings.borderWidth = width;
drawShape();
};
var drawShape = function() {
$('#' + settings.elementId).attr('class', settings.shape + " " + "center");
$('#' + settings.elementId).css({
'background-color': settings.color,
'border': settings.borderWidth + ' solid ' + settings.borderColor
});
$('#' + settings.elementId).html(settings.color + " " + settings.shape);
};
return this.each(function() {
settings.elementId = $(this).attr('id');
drawShape();
var myPlugin = {
element: $(this),
setBorder: function(color, width) {
setBorder(color, width);
return this.element;
},
color: function() {
return settings.color;
},
shape: function() {
return settings.shape;
},
inspectSettings: function() {
msg = "inspecting settings for element '" + settings.elementId + "':";
msg += "\n--- shape: '" + settings.shape + "'";
msg += "\n--- color: '" + settings.color + "'";
msg += "\n--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor + "'";
return msg;
},
change: function(shape, color) {
settings.shape = shape;
settings.color = color;
drawShape();
return this.element;
}
};
$(this).data("myPlugin", myPlugin);
});
};
}(jQuery));
现在,您可以使用以下语法调用内部插件方法来访问或修改插件数据或相关元素:
$("#...").data('myPlugin').myPublicPluginMethod();
只要在
myPublicPluginMethod()
的实现中从内部返回当前元素(this),jQuery链式调用就会保留,因此以下代码可以正常工作:
$("#...").data('myPlugin').myPublicPluginMethod().css("color", "red").html("....");
这里有一些例子(详细信息请查看此
fiddle):
$("#shape1").myPlugin({shape: 'square', color: 'blue', borderColor: 'SteelBlue'});
$("#shape2").myPlugin({shape: 'rectangle', color: 'red', borderColor: '#ff4d4d'});
$("#shape3").myPlugin({shape: 'circle', color: 'green', borderColor: 'LimeGreen'});
console.log($("#shape1").data('myPlugin').inspectSettings());
console.log($("#shape2").data('myPlugin').inspectSettings());
console.log($("#shape3").data('myPlugin').inspectSettings());
$("#shape1").data('myPlugin').change("circle", "green").fadeOut(2000).fadeIn(2000);
$("#shape1").data('myPlugin').setBorder('LimeGreen', '30px');
$("#shape2").data('myPlugin').change("rectangle", "red");
$("#shape2").data('myPlugin').setBorder('#ff4d4d', '40px').css({
'width': '350px',
'font-size': '2em'
}).slideUp(2000).slideDown(2000);
$("#shape3").data('myPlugin').change("square", "blue").fadeOut(2000).fadeIn(2000);
$("#shape3").data('myPlugin').setBorder('SteelBlue', '30px');