Lugo Labs

Custom Tabular plugins

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:

js
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 table
  • options - all options passed to Tabular
  • myOptions - 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:

js
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:

js
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.