Pew.js is a tiny progressive enhancement library whose main concern is to enhance HTML DOM fragments with Javascript objects while respecting the separation of concerns principles.
That means that you can leave your HTML untouched, and let Pew enhance it by giving the wanted DOM fragments to your JavaScript classes so they can work on them separately.
npm install pewjs --save
Write some pure HTML
<section>
<div id="test-component-1" class="test-component">
Test component 1
</div>
<div id="test-component-2" class="test-component">
Test component 2
</div>
<div id="test-component-3" class="test-component">
Test component 3
</div>
</section>
Create an instanciable JavaScript object
export class MyFrontEndComponent {
/**
* Element will receive the HTML DOM node from pew
*/
constructor(element, options) {
this.element = element;
this.options = options;
this.init();
}
init() {
console.log('This is MyFrontEndComponent instanciated with the HTML DOM node : '+this.element.id);
}
}
Instanciate Pew
let pew = new Pew();
Add entries to registry items :
The RegistryEntry first parameter is the key where your RegistryEntry is going to be stored in Pew's registry index (so you can retrieve it later for example)./
The RegistryEntry second parameter is your javascript object definition (not instanciated yet).
The RegistryEntry third parameter is your html selector. It can be a class, an id or even a data attribute.
pew.addRegistryEntry({classDef: MyFrontEndComponent, domSelector: '.test-component', key: 'myFrontEndComponentRegistryEntryKey'});
You can also instanciate registered Pew entries by your own.
Get the registered entry where you need it, for a fully free manipulation (or override of your registered items)
let accordion = pew.getRegistryEntry('accordion');
let DOM = document.body; // get a Dom Parent Element
new accordion.classDef(dom);
Or execute it when required before the automatic workflow
pew.enhanceRegistryEntry('accordion');
Run Pew whenever you need (ideally at the end of your call flow)
pew.enhanceRegistry();
In our example this is what is going to happen:
MyFrontEndComponent
with the current fragment in the constructor parameter.If we'd look in our browser console, we would see three logs :
In addition, Pew provides an internal debugger that you can activate like so : pew.debug()
;
If you did that, you'd see some additional messages like the following:
[PewJS DEBUG] RegistryItem : "myFrontEndComponentRegistryEntryKey" matched 3 results in ParentNode `<body>` with selector "`.test-component`" : `Array [ div.test-component ], [ div.test-component ], [ div.test-component ]`
#TL;DR :