Using CommonJS JavaScript Modules.
I have a module that I cannot edit or control. I call this the parent module.
I want to build on the parent’s functionality with additional features. Some of these child features need to use the functions in the parent. So I need to pass data to the parent and have it run like it was part of the parent module. The whole of the parent is exported.
Parent
function ParentModule () {
DefaultElement.setStatus = function (status, block) {
var statusBlock = block.querySelector('.' + this.statusBlock)
var statusText = status ? 'Available' : 'Out of Stock';
statusBlock.innerHTML = statusText;
}
}
Child
function ChildModule () {
UpdatedElement.update = function (el) {
var selected = document.getElementById(el)
var block = this.getBlock(selected)
window.ParentModule.DefaultElement.setStatus(true, block);
}
}
(Expected) Error
Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
What is the syntax or pattern for this?
Calling the relevant function within the child module, simply causes an error. As I understand this is expected – as the child module imports the parent function it runs within the child so doesn’t have access to the same data.
Rather than import into the child is there a way to have the child module simple behave like it was all one file? Or how can I pass data up to the parent and have it behave like it’s always been part of the parent?