views:

181

answers:

2

I'm creating a jQuery plugin for one of my projects and I was wondering what's the best way to go about this. I need to be able to call a function on the plugin from outside the plugin, at any time. For example, an event outside the plugin happens, and I want to say "plugin, do this". I've played around a bit and this works, but doesn't feel right.

In my plugin:

$.fn.myPlugin.update = function(element) {
    updateTable(element);   // this is a function within the plugin 
};

To call this function, I do this:

$('#someID').myPlugin.update();

This works, but the element param is null and I only have one element currently for this plugin. I think it would fail with multiple elements, since the function searches that element for specific children. What's the proper way to be able to to call a function within the plugin from outside it, and have it effect the element its attached to? I'm following this tutorial: http://www.learningjquery.com/2007/10/a-plugin-development-pattern

Thanks!

A: 

The element argument should be undefined because you're passing nothing to the update() function. If you want to refer to the contents of the jQuery object try:

jQuery.fn.myPlugin.update = function() {
  this.each(function() {
    updateTable(this);
  }
};

Also, you should apply your plugin to the jQuery object, not $. That article is giving you bad advice in that regard. Take a look at jQuery Plugins/Authoring.

cletus
+1  A: 

First of all, the elements selected are in the this variable. The elements are not passed to the function through your element parameter. So for instance:

$.fn.myPlugin.update = function(){
    updateTable(this);
}

should work perfectly. If you want to get the jQuery object associated with the selector just do

selector = $(this);

selector is the jQuery object that is the selector.

Samuel