Tabular is a small JavaScript library that builds tables using data fetched from the server. It comes with built-in plugins, such as sorting, searching, and pagination, but it also allows us to add our own custom plugins. Today we'll create our own tabular plugin, that will add a title to the page. Agreed, not very practical (we can just write it with HTML), but useful to illustrate the process. You can see a test for this on Tabular's Github repo.
The plugin
A typical Tabular plugin has this signature:
tabular.MyPlugin = function(element, options, myOptions) {
element.on('view:header.MyPlugin', function(e, header) {
header.prepend('<div class="my-title">' + myOptions.title + '</div>');
});
};
where:
element
- the main HTML element that contains the tableoptions
- all options passed to TabularmyOptions
- only plugin related options
We're hooking into the element's view:header
event, which is triggered by the Tabular View when the header is rendered. When that happens we render a div
element with a title taken from options passed to Tabular. Not how we've namespaced our event handler my:header.MyPlugin
, which we can use on to remove the handler on a destroy
method:
tabular.MyPlugin.prototype.destroy = function() {
element.off('view:header.MyPlugin');
};
This way we don't risk to remove other handlers from the element.
The setup
Note that we don't instantiate our plugin directly, this is done when starting Tabular:
tabular.start('#tabular', {
columns: [
{ name: 'name', title: 'Name' }
],
plugins: [
{
MyPlugin: {
title: 'People names'
}
}
]
});
Tabular will parse the options, and will instantiate our plugin by passing:
- an instance of the jQuery container element (
$(#tabular)
) - all the options
- our plugin options:
{ title: 'People names' }
Conclusion
If we put our plugin on a web page, we can see the title of the page showing as People names. Since the title has a my-title
CSS class, we can also style it as we wish.