views:

35

answers:

2

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?

A: 

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()

Hannes
+2  A: 

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.

Pointy