Background
I have a jQuery plugin I created, the plugin takes all table on a page and loads the rows by making a remote request.
Code Example
This is a simple example that heights the structured used by the plugin. In the actual example the load function makes an AJAX request and processes the result adds rows to the table.
JavaScript
(function($) {
$.table = function(el, options) {
// To avoid scope issues, use 'base' instead of 'this'
// to reference this class from internal events and functions.
var base = this;
// Access to jQuery and DOM versions of element
base.$el = $(el);
base.el = el;
base.load = function() {
base.$el.find('tbody:last').append("<tr><td>...</td><td>...</td></tr>");
};
base.load();
};
$.fn.table = function(options) {
options = options || {};
return this.find(options.selector)
.each(function(index) {
new $.table(this, options);
})
};
})(jQuery);;
HTML
<table id="table1" data-role="table">
<thead id="tour-table">
<tr>
<th data-id="id" width="20px">col1</th>
<th data-id="given_name">col2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<table id="table2" data-role="table">
<thead id="tour-table">
<tr>
<th data-id="id" width="20px">col1</th>
<th data-id="given_name">col2</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I initialise all the tables on a page like this.
$('body').table({selector:'[data-role="table"]'});
jsfiddle
You can see an example in action http://jsfiddle.net/RWy5r/1/
Question
Is it possible to expose the load function to the dom so that I can call it against the object something like this?
$("#table1").load();
or
$("#table1").table.load();
Using the simple example above the result would be that the table with ID "table1" would have the <td> appended and all other tables including the table with ID "table2" would remain unchanged.
This took me a little time to work out however the solution is very simple. All we need to do is add the object the plugin created to the dom so we can access it at a later time, jQuery already provides a way to do this via the .data() function.
Solution
Take a look at a working example http://jsfiddle.net/leviputna/RWy5r/5/
Explanation
When the plugin is initialised I am storing the the object created against the dom object so I can access it later.
$.data($(el).get(0), "table", this);Then I am exposing a public function that will find the object against a selection and call the load method.
Finally I added two on click functions to illustrate the process in action.
I hope this solution helps someone in the future.