sgoran sgoran - 1 year ago 115
Javascript Question

Building Javascript Modules

I have small library for client side routing and template loading.
It's built from several smaller module, for example Tpl, Router..

Every module check if library namespace is defined and than apply itself to it.

Here is the code:

For example Tpl component binds itself to Micro library (the main lib)

if(typeof Micro === "function" && Micro.prototype.isMicro){
Micro['Tpl'] = Tpl;

And than I am calling library with constructor

var micro = new Micro(properties);

Problem is if I want to make another instance...dependencies will collide internally

var micro2 = new Micro(properties);

For build, I use gulp and just concatenate modules to one file..

Can anyone propose a good way for building multiple modules to one, like sandboxing them?
Or some best practices and patterns without using webpack, requireJs etc..

Answer Source

You only have to get rid of all shared state within the Micro constructor itself. For instance, with = Micro.Pubsub; all instances will share the same Pubsub instance which is problematic, but you can solve that by instantiating a new Pubsub for every Micro instance. There is probably more shared state (e.g. document.querySelectorAll('[hub-link]')), but I haven't dug far.

Once you get rid of shared state within the Micro constructor, what would still be problematic though is to have multiple Micro instances using different sub-modules (e.g. Tpl, Routes). That is because you did not use any form of dependency inversion to resolve these sub-modules from within the Micro constructor.

That's probably not a problem though because I doubt a single application would ever use different sub-module implementations concurrently. Still, you may want to make dependencies explicit and allow to inject the sub-modules dependencies into the Micro constructor.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download