Skip to content
Ali Almossawi edited this page May 21, 2015 · 5 revisions

As of v2.5, it is now easier to extend the library, thanks to two improvements: looser coupling between charts and the library's core code, and the introduction of hooks. These changes are due to the tireless work of Dan de Havilland.

Charts are now self-contained components that register themselves with the library on first load. MG.chart maintains an array of registered chart types and calls the appropriate one in MG.data_graphic when needed. Chart-specific defaults, functions and logic are encapsulated within individual files under src/js/charts.

The library includes an initial set of hooks that allow one to execute arbitrary code at predefined points in the codebase. For instance, to add a new option, you would register the hook at global.defaults by calling MG.add_hook:

MG.add_hook('global.defaults', function(args) {
    args.enhanced_rollover = true;
});

In order to execute code before initializing a chart, you would register the hook at global.before_init:

MG.add_hook('global.before_init', function(args) {
    console.log("About to initialize a chart");
});

You can also add and call your own hooks. For instance:

function my_hook() {
    console.log("It's happening");
}

MG.add_hook('test', my_hook);
MG.call_hook('test');

There are additional examples of how to use MG.add_hook and MG.call_hook here.

Here are two addons that demonstrate how to use hooks to seamlessly incorporate new features into the library:

  • mg-color-scale – “extrapolates a scale of line colors based on predefined CSS rules”
  • mg-line-brushing – “adds simple drag-to-zoom functionality to the line chart”

You can see a demo of them here and here.

Related PRs and issues: 351, 344

Clone this wiki locally