Files
wordpress-theme-aksrt/assets/js/rehydrate.js
T

82 lines
2.5 KiB
JavaScript

/**
* AKSRT Rehydrate System
*
* Centralized component initialization and re-initialization system.
* Components register their init functions, and rehydrate() is called
* to initialize or re-initialize them on a given root element.
*
* Usage:
* AksrtFrontend.register('name', initFn); // Register a component
* AksrtFrontend.rehydrate(root, 'init'); // Initialize all components
*
* @package AKSRT
* @since 5.0.0
*/
(function () {
'use strict';
var _registry = [];
var _initialized = [];
window.AksrtFrontend = {
/**
* Register a component's init function.
*
* @param {string} name Unique component name
* @param {Function} initFn Function(root, reason) - root defaults to document
*/
register: function (name, initFn) {
if (typeof name !== 'string' || typeof initFn !== 'function') return;
// Prevent duplicate registrations
for (var i = 0; i < _registry.length; i++) {
if (_registry[i].name === name) {
_registry[i].initFn = initFn;
return;
}
}
_registry.push({ name: name, initFn: initFn });
},
/**
* Initialize or re-initialize all registered components on a root element.
*
* @param {Element|Document} root The root DOM element to search within
* @param {string} reason Why rehydrate is called:
* 'init' = initial page load
* 'ajax' = after AJAX content injection
* 'modal' = after modal content loads
* Custom string for other triggers
*/
rehydrate: function (root, reason) {
root = root || document;
reason = reason || 'init';
for (var i = 0; i < _registry.length; i++) {
var entry = _registry[i];
try {
entry.initFn(root, reason);
} catch (err) {
console.error('[AKSRT Rehydrate] Error initializing "' + entry.name + '":', err);
}
}
// Dispatch event so external scripts can hook in
try {
root.dispatchEvent(new CustomEvent('aksrt:rehydrated', {
bubbles: true,
detail: { reason: reason }
}));
} catch (e) { /* IE fallback */ }
},
/**
* Get the list of registered component names (for debugging).
*/
getRegistered: function () {
return _registry.map(function (r) { return r.name; });
}
};
})();