views:

115

answers:

2

I have written a jQuery plugin like this:

jQuery(function($) {
  $.fn.myPlugin = function() {
    return this.each(function () {
      this.publicFunction = function() {
        alert('test');
      };

      return this;
    });
  };
});

My JavaScript on my HTML page looks like this:

  var myPluginDiv = $("#divTest").myPlugin();
  myPluginDiv.publicFunction();

And I get the error "myPluginDiv.addItem is not a function." It's clearly a public function. Why is it not working?

A: 

You're adding the function to the DOM element, not the jQuery object being returned. myPluginDiv is a jQuery object. I think either of the following would work:

Apply to the returned jQuery object:

jQuery(function($) { 
  $.fn.myPlugin = function() { 
      this.publicFunction = function() {
          alert('test');
      }
      return this;
  };
});

var a = $('selector').myPlugin();
a.publicFunction();

or applied as in original question to DOM object:

myDivPlugin.get(0).publicFunction();

or

myDivPlugin.each( function() { this.publicFunction(); } );
tvanfosson
Well, your first solution didn't work. It seemed like your reasoning was sound, but when I tried it, it didn't work. However, the second solution worked. The .get(0) is the key.
Brandon Montgomery
Took a closer look at the code. The problem with it now is that it adds the function to each element of the iteration, not the jQuery object being returned. I'll add a couple of different (fixed) alternatives.
tvanfosson
A: 

Got it! I knew I'd had this problem before, I just couldn't remember what I did to fix it. The key is to use .get(0) at the end of my plugin call, like this:

var myPluginDiv = $("#divTest").myPlugin().get(0);

Then I can call myPluginDiv.publicFunction() without a problem.

Brandon Montgomery