Reputation: 43
I´ve tried a jQuery Plugin Boilerplate from this Site : jQuery_boilerplate, but i can´t call the public Method fooBar. My implemantion looks like:
/**
* jQuery lightweight plugin boilerplate
* Original author: @ajpiano
* Further changes, English comments: @addyosmani
* More further changes, German translation: @klarstil
* Licensed under the MIT license
*/
;(function ( $, window, document, undefined ) {
"use strict";
var pluginName = 'defaultPluginName',
defaults = {
propertyName: "value"
};
var privateMethod = function() {
};
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options) ;
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype.init = function () {
};
Plugin.prototype.fooBar = function(someValue) {
var fooBarModifier = 3;
function privateFooBar(someValue) {
return someValue * fooBarModifier;
}
someValue = privateFooBar(someValue);
return someValue;
};
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
For Example i use the Plugin like this:
$('#wrapper').defaultPluginName();
and i try to call the method like this:
$('#wrapper').fooBar();
But my Console gives me bck an this Error:
TypeError: $(...).fooBar is not a function $('#wrapper').fooBar();
How can I call a Method on this Selection?
Upvotes: 2
Views: 6840
Reputation: 388316
It is because $('#wrapper')
does not return an instance of the plugin, it returns a jQuery wrapper for the matched set of DOM elements which does not have the fooBar
method.
If you want to call the plugin's public method, try:
$('#wrapper').data('plugin_defaultPluginName').fooBar();
The plugin instance is stored as data to the element with name 'plugin_' + pluginName
, so:
$('#wrapper').data('plugin_defaultPluginName')
will return the instance of plugin named defaultPluginName
.fooBar();
calls the method fooBar
within the plugin instanceUpvotes: 7