Categories
Article javascript design patterns plugin

Designing a JavaScript Plugin System

WordPress has plugins. jQuery has plugins. Gatsby, Eleventy, and Vue do, too. Plugins are a common feature of libraries and frameworks, and for a good reason: they allow developers to add functionality, in a safe, scalable way. This makes the core project more valuable, and it builds a community — all without creating an additional maintenance burden. What a great deal! So how do you go about building a plugin system? Let’s answer that question by building one of our own, in JavaScript. I’m using the word “plugin” but these things are sometimes called other names, like “extensions,” “add-ons,” or “modules.” Whatever you call them, the concept (and benefit) is the same. Let’s build a plugin system Let’s start with an example project called BetaCalc. The goal for BetaCalc is to be a minimalist JavaScript calculator that other developers can add “buttons” to. Here’s some basic code to get us started: // The Calculator const betaCalc = {   currentValue: 0,      setValue(newValue) {     this.currentValue = newValue;     console.log(this.currentValue);   },      plus(addend) {     this.setValue(this.currentValue + addend);   },      minus(subtrahend) {     this.setValue(this.currentValue – subtrahend);   } }; 
 // Using the calculator betaCalc.setValue(3); // => 3 betaCalc.plus(3);     // => 6 betaCalc.minus(2);    // => 4 We’re defining our calculator as an object-literal to keep things simple. The calculator works by printing its result via console.log. Functionality is really limited right now. We have a setValue method, which takes a number and displays it on the “screen.” We also have plus and minus methods, which will perform an operation on the currently displayed value. It’s time to add more functionality. Let’s start by creating a plugin system. The world’s smallest plugin system We’ll start by creating a register method that other developers can use to register a plugin with BetaCalc. The job of this method is simple: take the external plugin, grab its exec function, and attach it to our calculator as a new method: // The Calculator const betaCalc = {   // …other calculator code up here 
   register(plugin) {     const { name, exec } = plugin;     this[name] = exec;   } }; And here’s an example plugin, which gives our calculator a “squared” button: // Define the plugin const squaredPlugin = {   name: ‘squared’,   exec: function() {  …

Read the rest Designing a JavaScript Plugin System

Read at the original Source: css tricks.