views:

31

answers:

2

I am writing a jQuery plugin and need functions that can be called from inside as well as outside the plugin. Here is my code so far:

(function($){
 $.fn.bxSlider = function(options){

  var defaults = {
   mode : 'horizontal',
   speed : 500
  }

  var options = $.extend(defaults, options);

  var base = this;

  this.each(function(){   
   var someText = base.getText;
   console.log(someText);
  });

  this.getText = function(){
   return base.children().text();
  }

  return this;

 } 

})(jQuery);

When I call getText() from outside the plugin - it works just fine:

$(function(){
 var slider = $('ul').bxSlider();
 var text = slider.getText();
 $('body').append(text);
});

But when I try to call the function inside the plugin, I get a "function is not defined" error. Am I using the wrong syntax?

Thanks!

+1  A: 

You're calling it before you've added it to that jQuery object.

Try this:

  var base = this;

  this.getText = function(){
   return base.children().text();
  }

  this.each(function(){   
   var someText = base.getText;
   console.log(someText);
  });
patrick dw
Perfect! Totally worked!
wandoledzep
A: 

It appears that you're adding the method getText onto each instance, and trying to call it before definition. You could either:

  1. Switch the order of your this.each and this.getText = so that you assign getText first
  2. Assign getText the same way you've assigned bxSlider, by extending $.fn. This way it will be on the prototype of all jQuery objects. You'll probably want to build in some logic to verify an error is thrown if you call getText before calling bxSlider on an object.
bcherry