Accessing jQuery-Plugin-Methods + -Data From The Outside
Usage of the jQuery-data()-method to provide a public interface to internal plugin-methods / data
by Mayinx
HTML
<div id="shape1"></div>
<div id="shape2"></div>
<div id="shape3"></div>
CSS
.square {
width: 200px;
height: 200px;
}
.rectangle {
width: 300px;
height: 200px;
}
.circle {
width: 200px;
height: 200px;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
border-radius: 50%;
}
.oval {
width: 300px;
height: 200px;
-moz-border-radius: 150px / 100px;
-webkit-border-radius: 150px / 100px;
border-radius: 150px / 100px;
}
.center{
color: white;
text-align: center;
vertical-align: middle;
line-height: 200px;
margin: 20px;
display: block;
margin-left: auto;
margin-right: auto;
font-family: Impact;
font-size: 1.5em;
}
JavaScript
(function($, window, undefined) {
$.fn.myPlugin = function(options) {
// settings, e.g.:
var settings = $.extend({
elementId: null,
shape: "square",
color: "aqua",
borderWidth: "10px",
borderColor: "DarkGray"
}, options);
// private methods, e.g.:
var setBorder = function(color, width) {
console.log(
"Setting border for element '" + settings.elementId + "' to '" + width + " solid " + color + "'"
);
settings.borderColor = color;
settings.borderWidth = width;
drawShape();
};
var drawShape = function() {
console.log("Drawing shape for element '" + settings.elementId + "'");
console.log("--- shape: '" + settings.shape);
console.log("--- color: '" + settings.color);
console.log("--- border: '" + settings.borderWidth + ' solid ' + settings.borderColor);
$('#' + 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() { // jQuery chainability
// set stuff on ini, e.g.:
settings.elementId = $(this).attr('id');
drawShape();
// PUBLIC INTERFACE
// gives us stuff like:
//
// $("#...").data('myPlugin').myPublicPluginMethod();
//
var myPlugin = {
element: $(this),
// access private plugin methods, e.g.:
setBorder: function(color, width) {
setBorder(color, width);
return this.element; // To ensure jQuery chainability
},
// access plugin settings, e.g.:
color: function() {
return settings.color;
},
// access setting...