Odo Module
Augment a class' static methods with helpers.
We think of a module as a section of the page which is made up of components. When they appear on the page, we want to initialize them. One pattern is to add a static initialize
method to every module class created. This component simplifies this by moving the static methods out of the module.
OdoModule is similar to a mixin, but it needs to know about the class it's augmenting.
Support
IE9+
Dependencies
None
API
register(Module[, selector])
Adds the static methods (listed below) to Module
. selector
is the base selector for the module, representing its main element.
If selector isn't defined, the component will look for enumerations with the selector: Module.Selectors.BASE
, Module.ClassName.BASE
, and Module.Classes.BASE
.
OdoModule.register(CoolModule);
unregister(Module[, selector])
Forgets about Module
. Currently leaves the added methods and instances as-is in case they're needed.
OdoModule.unregister(CoolModule);
Class Methods
initializeAll(context = document, options = {})
Initialize all elements within context
. This method returns a Map of the instances which were creatd. It also adds the new instances to the static Instances
property on the class.
CoolModule.initializeAll(containingElement)
initializeWhenIdle(context, options)
Initialize all elements within context
when the browser has a moment of idle time. This method returns a Promise which resolves when the module(s) have been initialized. This method just calls initializeAll
within a requestIdleCallback
which uses the request-idle-callback package. This method is useful for deferring the initialization of modules which are not above-the-fold on page load.
CoolModule.initializeWhenIdle(containingElement)
disposeAll(context = document)
Dispose of all instances from within a context.
CoolModule.disposeAll(containingElement)
getInstance(element)
Retrieve the instance by its main element.
CoolModule.getInstance(element)
deleteInstance(element)
Removes the instance from the Instances
map and calls its dispose
method if it has one.
CoolModule.deleteInstance(element)
Full Example
Let's say you have a base component which does this:
class BaseComponent {
constructor(element) {
this.element = element;
}
getAllByClass(className) {
return Array.from(this.element.getElementsByClassName(className));
}
}
And your module wants to console.log
all classes matching 'child'
.
class CoolModule extends BaseComponent {
constructor(element) {
super(element);
console.log(this.getChildren());
}
getChildren() {
return this.getAllByClass(CoolModule.Classes.CHILD);
}
}
CoolModule.Classes = {
BASE: 'cool-module',
CHILD: 'cool-module__child',
};
// Register with OdoModule.
OdoModule.register(CoolModule);
// Find all occurances of '.cool-module' and initialize them.
CoolModule.initializeAll();
initializeAll
also returns a map of the instances which were created if you need them.