Reputation: 1484
I read a lot about it but what i undertand is not working.
I'm using this jquery plugin boilerplate.
i have a plugin called "defaultPluginName" and i have a public method inside plugin:
sayHey: function(){
alert('Hey!');
}
i want call this method outsise, something like that:
$('#test').defaultPluginName('sayHey');
but is not working, follow here a fidle link to give you a better view about my issue: http://jsfiddle.net/TCxWj/
Upvotes: 0
Views: 2215
Reputation: 15213
The method your are trying to call is not public so you need to alter your plugin in order to trigger it from outside the plugin.
See here how you can do that: https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Another-extending-jQuery-boilerplate.
Basically you need to change
$.fn[ pluginName ] = function ( options ) {
return this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
};
To
$.fn[pluginName] = function ( arg ) {
var args, instance;
// only allow the plugin to be instantiated once
if (!( this.data( 'plugin_' + pluginName ) instanceof Plugin )) {
// if no instance, create one
this.data( 'plugin_' + pluginName, new Plugin( this ) );
}
instance = this.data( 'plugin_' + pluginName );
/*
* because this boilerplate support multiple elements
* using same Plugin instance, so element should set here
*/
instance.element = this;
// Is the first parameter an object (arg), or was omitted,
// call Plugin.init( arg )
if (typeof arg === 'undefined' || typeof arg === 'object') {
if ( typeof instance['init'] === 'function' ) {
instance.init( arg );
}
// checks that the requested public method exists
} else if ( typeof arg === 'string' && typeof instance[arg] === 'function' ) {
// copy arguments & remove function name
args = Array.prototype.slice.call( arguments, 1 );
// call the method
return instance[arg].apply( instance, args );
} else {
$.error('Method ' + arg + ' does not exist on jQuery.' + pluginName);
}
};
Then it will pick up your method.
Hope it helps.
Upvotes: 2