Reputation: 1862
Is there a way to call a method defined in a jQuery plugin directly in my script?
update
(function($){
$.fn.myPlugin = function (options) {
return this.each(function() {
function doSomething() {
// do something
}
function doSomethingElse() {
// do something else
}
doSomething();
doSomethingElse();
});
}
})(window.jQuery);
now i want to call doSomethingElse() from my script. Is there a way to do this?
Upvotes: 2
Views: 3990
Reputation: 332
In my opinion best is to use event system when you nedd to call it from outside. Here is the result with your code:
(function($){
$.fn.myPlugin = function (options) {
return this.each(function() {
var $this = $(this);
$this.on('doSomething', function() {
// do something
}
$this.on('doSomethingElse', function() {
// do something else
}
$this.trigger('doSomethingElse');
$this.trigger('doSomething');
});
}
})(window.jQuery);
or call it from outisde with same method:
$('.myPluginDiv').trigger('doSomethingElse');
$('.myPluginDiv').trigger('doSomething');
Upvotes: 2
Reputation: 884
You can also use events so the plugin is listening for an event with bind and then you call trigger. Could be a target like window etc.
Upvotes: 0
Reputation: 413702
The direct answer to your question is, "no". As posted, that code explicitly hides those functions from the outside world.
One jQuery-ish way to make those functions available is to define them differently. Personally, I like to create plugins that have a corresponding "global" object, so if I have
$.fn.pointy = function() {
// plugin
}
I'll also have:
$.pointy = {
something: function() { ... },
somethingElse: function() { ... }
}
That's nice for providing both relevant utilities and also configuration APIs. Thus you could put your "doSomething" functions there, and then use them inside your plugin by qualifying the names as $.myPlugin.doSomething()
. Of course you can also create the functions inside your plugin initialization, so that they might be closures with access to other private functions.
Upvotes: 4
Reputation: 8237
I'm not a 100% sure i get you, but after defining a new function you can still cal it outside of the jQuery Selection, see:
$.fn.myfunc = function(){
alert('foo');
}
$.fn.myfunc(); // works
$('#something').myfunc(); // works too
So you would have to find out exactly how the methods needs to be called and then do it via $.fn.func()
Upvotes: 0