TOP 3 patterns for JavaScript libraries
Fast review of “must-have” patterns to write JS libraries like a boss
I will warn in advance that it’s just a short post to remind you about some useful patterns and maybe you’ll rethink your code. More detailed posts about its usage will be a little later.
So, I don’t want to write extra lyrics, just let me start.
Observer
Easiest way to realize interactions (both external and internal) in library — create event bus and just send/listen events. Much of cases when you need to interact with parts of library or with your application.
- Pretty simple to use
- Nice to organize library APIs when you need to handle smth
Just 119 bytes and no additional actions with nanoevents
Middleware
Middleware is an additional layer for your library that allows you to catch actions, modify it, cancel or do anything you want. It’s really nice way to add opportunity to create plugins without pain.
But that’s not only one feature. In context of nano-libraries middleware allows you to move a small part of features out of library core and use them only if we need it.
- Allows you to extend functional with plugins
- Greatly reduces boilerplate code when using your library
- In some cases it’s must-have to modify or cancel actions
Just 342 bytes and no additional actions with koa-compose
Mixins
Mixin is just a function that accepts instance and modifies it by adding new properties, methods or doing some things inside instance. Also mixin may have 2nd argument with options that are passed from 2nd argument of .install
method
- You can move optional features outside core and use them only if needed
- Most comfortable way to customize instances of smth
- Really reduces boilerplate code too (’cause we can make reusable plugins)
Implementation is so easy. Just 3 lines of code and you become stronger.
If you’re FP ninja (like me) and don’t want to mutate instance and create the new one, you may wrap this
with nanoclone (220 bytes) to clone instance and modify it.
Conclusion
So if we get a power of this trinity, we’ll get:
- Easy-to-use library with really no problems to work with in any cases. If you can make it simpler — you’re welcome, 50 claps and mention in that post guaranteed :)
- Low-level API lets you build an entire ecosystem around your library with plugins and events handling. Plugins may have their own events too and it’s nice too
- And, most importantly, we can make really tiny library core. The above patterns let us make additional or optional features in separated files
So, if you are interested, you can see my new library — NanoTween. It uses observers to handle specific events and mixins to have more way to customize and simplify work with library.
So, that’s all, I think :)