How to create a Tom Select plugin
masterPlugins are implemented as functions that receive plugin_options and are executed within the context of a TomSelect instance (this).
Structure Requirements
- Location: Files should live in
src/plugins/[plugin_name]/. - Naming: Plugin names must follow the format
/[a-z_]+$/. - Files:
plugin.js(Required): Contains the exported function.plugin.scss(Optional): CSS that will be bundled at build time.
- Registration: Do not call
TomSelect.defineinside the plugin file itself; call it when importing the plugin.
Plugin Lifecycle and Hooks
Plugins are initialized right before the control is setup. To interact with the control's lifecycle, use the following patterns:
Adding Dependencies
Use this.require('plugin_name') to ensure other plugins are loaded.
Method Hooks
Use this.hook(type, method, callback) to execute code around existing methods.
after: Runs after the method.before: Runs before the method.instead: Used to override a method. Note: If the original method returns a value, your overridden function must also return a value.
DOM Events
To add event listeners to DOM elements, use the after hook on the setup method to ensure the control elements exist.
// Boilerplate: src/plugins/plugin_name/plugin.js
export default function(plugin_options) {
// plugin_options: plugin-specific options
// this: TomSelect instance
};
// Adding Dependencies
export default function(plugin_options) {
this.require('another_plugin');
};
// Method Hooks (after)
export default function(plugin_options) {
this.hook('after', 'setup', function() {
// .. additional setup
});
};
// Overriding Methods (instead)
export default function(plugin_options) {
var original_setup = this.setup;
this.hook('instead', 'setup', function() {
// .. custom setup
return original_setup.apply(this, arguments);
});
};
// DOM Events
export default function(plugin_options) {
this.hook('after', 'setup', function() {
this.control.addEventListener('click',function(evt){
alert('the control was clicked');
});
});
};