Advanced JavaScript Development
Modern patterns, async, and modular architecture that survives a second developer
There’s a moment in most portal projects where the JavaScript stops being a few event handlers and becomes an application. Usually nobody notices until it’s already unmaintainable.
This post is about writing the client-side code the way you’d write anything else you had to support: modular, tested, with error handling that isn’t an afterthought.
Step by step
1. Structure your code
Class-based architecture, since you’ll want the encapsulation:
// Portal manager with private fields (ES2022)
class PortalManager {
#apiClient;
#configuration;
#listeners = [];
static VERSION = '2.1.0';
constructor(config = {}) {
// Destructuring with defaults
const {
apiEndpoint = '/_api',
enableCache = true,
...additionalConfig
} = config;
this.#configuration = { apiEndpoint, enableCache, ...additionalConfig };
this.#apiClient = new APIClient({ baseURL: apiEndpoint });
this.#setupEventListeners();
}
// Read records from a Web API entity set, with retry
async fetchData(entitySet, options = {}) {
const {
select = [],
filter,
top = 10,
cache = this.#configuration.enableCache,
retries = 3
} = options;
if (!entitySet || typeof entitySet !== 'string') {
throw new TypeError('entitySet must be a non-empty string');
}
const query = new URLSearchParams();
if (select.length > 0) query.set('$select', select.join(','));
if (filter) query.set('$filter', filter);
query.set('$top', String(top));
const result = await this.#executeWithRetry(
() => this.#apiClient.get(`${entitySet}?${query}`, { cache }),
retries
);
return result.value;
}
// Event delegation, with every listener tracked for removal
#setupEventListeners() {
this.#listen(document, 'click', event => this.#handleGlobalClick(event));
this.#listen(window, 'pagehide', () => this.destroy());
}
#listen(target, type, handler, options) {
target.addEventListener(type, handler, options);
this.#listeners.push(() => target.removeEventListener(type, handler, options));
}
#handleGlobalClick(event) {
const actionElement = event.target.closest('[data-action]');
if (!actionElement) return;
const { action, entity } = actionElement.dataset;
event.preventDefault();
this.#executeAction(action, entity).catch(error => {
console.error(`Action ${action} failed:`, error);
});
}
async #executeAction(actionName, entitySet) {
const actionMap = new Map([
['fetchRecords', () => this.fetchData(entitySet, { select: ['name'] })]
]);
const actionHandler = actionMap.get(actionName);
if (!actionHandler) {
throw new Error(`Unknown action: ${actionName}`);
}
return actionHandler();
}
// Retry with exponential backoff; 4xx responses are not retried
async #executeWithRetry(operation, retries = 3, delay = 1000) {
let lastError;
for (let attempt = 1; attempt <= retries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
const clientError = error.status >= 400 && error.status < 500;
if (clientError || attempt === retries) {
throw error;
}
const backoffDelay = delay * Math.pow(2, attempt - 1);
console.warn(`Operation failed, retrying (${attempt}/${retries}):`, error.message);
await this.#sleep(backoffDelay);
}
}
throw lastError;
}
#sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
destroy() {
this.#listeners.forEach(remove => remove());
this.#listeners = [];
this.#apiClient.clearCache();
}
// Copy, so callers cannot modify the private configuration
get configuration() {
return structuredClone(this.#configuration);
}
static create(config) {
return new PortalManager(config);
}
}
The Web API lives at /_api/<entityset>, and every call to it, reads included, carries the request verification token from shell.getTokenDeferred() in the __RequestVerificationToken header. The API client below adds it.
And a module system, so dependencies are explicit rather than implied by script tag order:
// ES6 Module with Advanced Exports
// utils/dataProcessor.js
export class DataProcessor {
static #transforms = new Map();
// Register custom transform functions
static registerTransform(name, transformFn) {
if (typeof transformFn !== 'function') {
throw new TypeError('Transform must be a function');
}
this.#transforms.set(name, transformFn);
}
// Apply transforms in sequence
static async applyTransforms(data, transformNames = []) {
return await transformNames.reduce(async (accPromise, transformName) => {
const acc = await accPromise;
const transform = this.#transforms.get(transformName);
if (!transform) {
throw new Error(`Transform '${transformName}' not found`);
}
return await transform(acc);
}, Promise.resolve(data));
}
}
// Default transforms
DataProcessor.registerTransform('normalize', (data) => {
return Array.isArray(data) ? data : [data];
});
DataProcessor.registerTransform('validate', (data) => {
return data.filter(item => item && typeof item === 'object');
});
DataProcessor.registerTransform('enrich', async (data) => {
return Promise.all(data.map(async item => ({
...item,
id: item.id || crypto.randomUUID(),
timestamp: new Date().toISOString()
})));
});
export default DataProcessor;
// Advanced API Client Module
// services/apiClient.js
export class APIClient {
#baseURL;
#defaultHeaders;
#cache;
#requestInterceptors;
#responseInterceptors;
constructor(config = {}) {
this.#baseURL = config.baseURL || '';
this.#defaultHeaders = {
'Content-Type': 'application/json',
...config.headers
};
this.#cache = new Map();
this.#requestInterceptors = [];
this.#responseInterceptors = [];
}
// Interceptor methods for middleware pattern
addRequestInterceptor(interceptor) {
this.#requestInterceptors.push(interceptor);
return () => {
const index = this.#requestInterceptors.indexOf(interceptor);
if (index > -1) {
this.#requestInterceptors.splice(index, 1);
}
};
}
addResponseInterceptor(interceptor) {
this.#responseInterceptors.push(interceptor);
return () => {
const index = this.#responseInterceptors.indexOf(interceptor);
if (index > -1) {
this.#responseInterceptors.splice(index, 1);
}
};
}
// Advanced request method with full HTTP support
async request(method, endpoint, options = {}) {
const {
data,
headers = {},
cache = false,
timeout = 30000,
signal,
...fetchOptions
} = options;
// Build full URL; baseURL is a site-relative path, so no URL constructor
const url = `${this.#baseURL.replace(/\/$/, '')}/${endpoint.replace(/^\//, '')}`;
// Check cache first
if (cache && method === 'GET') {
const cached = this.#cache.get(url);
if (cached && Date.now() < cached.expires) {
return cached.data;
}
}
// Prepare request config
let requestConfig = {
method,
headers: { ...this.#defaultHeaders, ...headers },
signal: signal || AbortSignal.timeout(timeout),
...fetchOptions
};
// Add body for non-GET requests
if (data && !['GET', 'HEAD'].includes(method)) {
requestConfig.body = JSON.stringify(data);
}
// Power Pages Web API: request verification token on every call
if (url.startsWith('/_api/')) {
requestConfig.headers['__RequestVerificationToken'] = await this.#getRequestToken();
}
// Apply request interceptors
for (const interceptor of this.#requestInterceptors) {
requestConfig = await interceptor(requestConfig) || requestConfig;
}
try {
// Execute request
const response = await fetch(url, requestConfig);
// Apply response interceptors
let processedResponse = response;
for (const interceptor of this.#responseInterceptors) {
processedResponse = await interceptor(processedResponse) || processedResponse;
}
// Handle response
if (!processedResponse.ok) {
throw new HTTPError(
`HTTP ${processedResponse.status}: ${processedResponse.statusText}`,
processedResponse.status,
processedResponse
);
}
// Parse response
const responseData = await this.#parseResponse(processedResponse);
// Cache successful GET requests
if (cache && method === 'GET') {
this.#cache.set(url, {
data: responseData,
expires: Date.now() + (cache === true ? 300000 : cache) // 5 min default
});
}
return responseData;
} catch (error) {
if (error.name === 'AbortError') {
throw new TimeoutError(`Request timeout after ${timeout}ms`);
}
throw error;
}
}
// Convenience methods
get(endpoint, options = {}) {
return this.request('GET', endpoint, options);
}
post(endpoint, data, options = {}) {
return this.request('POST', endpoint, { ...options, data });
}
put(endpoint, data, options = {}) {
return this.request('PUT', endpoint, { ...options, data });
}
patch(endpoint, data, options = {}) {
return this.request('PATCH', endpoint, { ...options, data });
}
delete(endpoint, options = {}) {
return this.request('DELETE', endpoint, options);
}
// Advanced batch request method
async batch(requests) {
const results = await Promise.allSettled(
requests.map(({ method, endpoint, ...options }) =>
this.request(method, endpoint, options)
)
);
return results.map((result, index) => ({
request: requests[index],
success: result.status === 'fulfilled',
data: result.status === 'fulfilled' ? result.value : null,
error: result.status === 'rejected' ? result.reason : null
}));
}
#getRequestToken() {
return new Promise((resolve, reject) => {
shell.getTokenDeferred().done(resolve).fail(reject);
});
}
// Response parsing with content type detection
async #parseResponse(response) {
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
return await response.json();
} else if (contentType.includes('text/')) {
return await response.text();
} else if (contentType.includes('application/octet-stream')) {
return await response.arrayBuffer();
} else {
return await response.blob();
}
}
clearCache() {
this.#cache.clear();
}
}
// Custom error classes
export class HTTPError extends Error {
constructor(message, status, response) {
super(message);
this.name = 'HTTPError';
this.status = status;
this.response = response;
}
}
export class TimeoutError extends Error {
constructor(message) {
super(message);
this.name = 'TimeoutError';
}
}
2. Handle async
// Advanced Observable Pattern Implementation
class Observable {
constructor(subscribeFn) {
this._subscribeFn = subscribeFn;
}
subscribe(observer) {
const subscription = this._subscribeFn(observer);
return {
unsubscribe: subscription?.unsubscribe || (() => {})
};
}
// Transformation operators
map(transformFn) {
return new Observable(observer => {
return this.subscribe({
next: value => observer.next(transformFn(value)),
error: error => observer.error(error),
complete: () => observer.complete()
});
});
}
filter(predicateFn) {
return new Observable(observer => {
return this.subscribe({
next: value => {
if (predicateFn(value)) {
observer.next(value);
}
},
error: error => observer.error(error),
complete: () => observer.complete()
});
});
}
debounce(delay) {
return new Observable(observer => {
let timeoutId;
return this.subscribe({
next: value => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => observer.next(value), delay);
},
error: error => observer.error(error),
complete: () => observer.complete()
});
});
}
throttle(delay) {
return new Observable(observer => {
let lastEmit = 0;
return this.subscribe({
next: value => {
const now = Date.now();
if (now - lastEmit >= delay) {
lastEmit = now;
observer.next(value);
}
},
error: error => observer.error(error),
complete: () => observer.complete()
});
});
}
// Combination operators
static merge(...observables) {
return new Observable(observer => {
const subscriptions = observables.map(obs =>
obs.subscribe(observer)
);
return {
unsubscribe: () => subscriptions.forEach(sub => sub.unsubscribe())
};
});
}
static combineLatest(...observables) {
return new Observable(observer => {
const values = new Array(observables.length);
const hasValue = new Array(observables.length).fill(false);
let completedCount = 0;
const subscriptions = observables.map((obs, index) =>
obs.subscribe({
next: value => {
values[index] = value;
hasValue[index] = true;
if (hasValue.every(Boolean)) {
observer.next([...values]);
}
},
error: error => observer.error(error),
complete: () => {
completedCount++;
if (completedCount === observables.length) {
observer.complete();
}
}
})
);
return {
unsubscribe: () => subscriptions.forEach(sub => sub.unsubscribe())
};
});
}
// Factory methods
static fromEvent(element, eventName) {
return new Observable(observer => {
const handler = event => observer.next(event);
element.addEventListener(eventName, handler);
return {
unsubscribe: () => element.removeEventListener(eventName, handler)
};
});
}
static fromPromise(promise) {
return new Observable(observer => {
promise
.then(value => {
observer.next(value);
observer.complete();
})
.catch(error => observer.error(error));
});
}
static interval(delay) {
return new Observable(observer => {
let count = 0;
const intervalId = setInterval(() => {
observer.next(count++);
}, delay);
return {
unsubscribe: () => clearInterval(intervalId)
};
});
}
}
// Advanced Async Controller for Power Pages
class AsyncController {
constructor() {
this.activeOperations = new Map();
this.operationQueue = [];
this.maxConcurrent = 5;
this.defaultTimeout = 30000;
}
// Execute async operation with advanced control
async execute(operationId, asyncFn, options = {}) {
const {
timeout = this.defaultTimeout,
retries = 3,
priority = 'normal',
cancelPrevious = false,
dependencies = []
} = options;
// Cancel previous operation if requested
if (cancelPrevious && this.activeOperations.has(operationId)) {
this.cancel(operationId);
}
// Wait for dependencies
if (dependencies.length > 0) {
await this.waitForOperations(dependencies);
}
// Queue operation if at max capacity; resolves when it eventually runs
if (this.activeOperations.size >= this.maxConcurrent) {
return this.queueOperation(operationId, asyncFn, options);
}
return this.executeImmediate(operationId, asyncFn, { timeout, retries, priority });
}
async executeImmediate(operationId, asyncFn, options) {
const { timeout, retries, priority } = options;
// Create abort controller for cancellation
const abortController = new AbortController();
const timeoutId = setTimeout(() => abortController.abort(), timeout);
const operation = {
id: operationId,
abortController,
timeoutId,
priority,
startTime: Date.now()
};
this.activeOperations.set(operationId, operation);
try {
// Execute with retry logic
const result = await this.executeWithRetry(
() => asyncFn(abortController.signal),
retries,
abortController.signal
);
return result;
} catch (error) {
if (error.name === 'AbortError') {
throw new Error(`Operation ${operationId} was cancelled`);
}
throw error;
} finally {
// Cleanup
clearTimeout(timeoutId);
this.activeOperations.delete(operationId);
// Process queued operations
this.processQueue();
}
}
async executeWithRetry(operation, retries, signal) {
let lastError;
for (let attempt = 1; attempt <= retries; attempt++) {
if (signal.aborted) {
throw new DOMException('Operation aborted', 'AbortError');
}
try {
return await operation();
} catch (error) {
lastError = error;
if (attempt === retries || signal.aborted) {
throw error;
}
// Exponential backoff
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 10000);
await this.sleep(delay, signal);
}
}
throw lastError;
}
async queueOperation(operationId, asyncFn, options) {
return new Promise((resolve, reject) => {
this.operationQueue.push({
id: operationId,
asyncFn,
options,
resolve,
reject
});
// Sort queue by priority
this.operationQueue.sort((a, b) => {
const priorities = { high: 3, normal: 2, low: 1 };
return priorities[b.options.priority || 'normal'] -
priorities[a.options.priority || 'normal'];
});
});
}
processQueue() {
while (this.operationQueue.length > 0 &&
this.activeOperations.size < this.maxConcurrent) {
const queuedOperation = this.operationQueue.shift();
const { id, asyncFn, options, resolve, reject } = queuedOperation;
const settings = {
timeout: options.timeout ?? this.defaultTimeout,
retries: options.retries ?? 3,
priority: options.priority || 'normal'
};
// Not awaited, so several queued operations can run at once
this.executeImmediate(id, asyncFn, settings).then(resolve, reject);
}
}
cancel(operationId) {
const operation = this.activeOperations.get(operationId);
if (operation) {
operation.abortController.abort();
return true;
}
// Remove from queue if not yet started
const queueIndex = this.operationQueue.findIndex(op => op.id === operationId);
if (queueIndex !== -1) {
const queuedOperation = this.operationQueue.splice(queueIndex, 1)[0];
queuedOperation.reject(new Error(`Operation ${operationId} was cancelled`));
return true;
}
return false;
}
cancelAll() {
// Cancel active operations
for (const [id, operation] of this.activeOperations) {
operation.abortController.abort();
}
// Cancel queued operations
while (this.operationQueue.length > 0) {
const queuedOperation = this.operationQueue.shift();
queuedOperation.reject(new Error('All operations cancelled'));
}
}
async waitForOperations(operationIds) {
const checkInterval = 100;
while (operationIds.some(id => this.activeOperations.has(id))) {
await this.sleep(checkInterval);
}
}
sleep(ms, signal) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(resolve, ms);
if (signal) {
signal.addEventListener('abort', () => {
clearTimeout(timeoutId);
reject(new DOMException('Sleep aborted', 'AbortError'));
});
}
});
}
getStatus() {
return {
activeOperations: this.activeOperations.size,
queuedOperations: this.operationQueue.length,
operations: Array.from(this.activeOperations.entries()).map(([id, op]) => ({
id,
priority: op.priority,
duration: Date.now() - op.startTime
}))
};
}
}
Async bugs are the expensive kind - they only show up under load, on someone else’s connection, and never on your machine.
3. Build components, not pages
// Base Component Class with Advanced Features
class Component {
static #registry = new Map();
static #globalMixins = [];
#element;
#props;
#state;
#subscriptions;
#childComponents;
#isDestroyed;
constructor(element, props = {}) {
this.#element = element;
this.#props = { ...props };
this.#state = {};
this.#subscriptions = [];
this.#childComponents = new Set();
this.#isDestroyed = false;
// Apply global mixins
Component.#globalMixins.forEach(mixin => {
Object.assign(this, mixin);
});
// Initialize component
this.created();
this.render();
this.mounted();
}
// Lifecycle methods (to be overridden)
created() {}
mounted() {}
updated() {}
destroyed() {}
// State management
setState(newState, callback) {
if (this.#isDestroyed) return;
const prevState = { ...this.#state };
this.#state = { ...this.#state, ...newState };
// Trigger update
this.updated(prevState, this.#state);
this.render();
// Execute callback after update
if (callback) {
requestAnimationFrame(callback);
}
}
getState() {
return { ...this.#state };
}
// Props management
setProps(newProps) {
if (this.#isDestroyed) return;
const prevProps = { ...this.#props };
this.#props = { ...this.#props, ...newProps };
this.propsChanged(prevProps, this.#props);
this.render();
}
getProps() {
return { ...this.#props };
}
propsChanged(prevProps, newProps) {}
// Event system
emit(eventName, detail = {}) {
const event = new CustomEvent(eventName, {
detail: { component: this, ...detail },
bubbles: true,
cancelable: true
});
this.#element.dispatchEvent(event);
return event;
}
on(eventName, handler, options = {}) {
const element = this.#element;
element.addEventListener(eventName, handler, options);
// Track subscription for cleanup; same capture value, or it is not removed
const cleanup = () => element.removeEventListener(eventName, handler, options);
this.#subscriptions.push(cleanup);
return cleanup;
}
// Child component management
createChildComponent(ComponentClass, element, props) {
const child = new ComponentClass(element, props);
this.#childComponents.add(child);
return child;
}
destroyChildComponent(child) {
if (this.#childComponents.has(child)) {
child.destroy();
this.#childComponents.delete(child);
}
}
// Private fields are not visible to subclasses, so expose the element
get element() {
return this.#element;
}
// DOM utilities
$(selector) {
return this.#element.querySelector(selector);
}
$$(selector) {
return Array.from(this.#element.querySelectorAll(selector));
}
// Template rendering (to be overridden)
render() {
// Default implementation - override in subclasses
}
// Cleanup
destroy() {
if (this.#isDestroyed) return;
this.#isDestroyed = true;
// Destroy child components
this.#childComponents.forEach(child => child.destroy());
this.#childComponents.clear();
// Clean up subscriptions
this.#subscriptions.forEach(cleanup => cleanup());
this.#subscriptions = [];
// Call lifecycle method
this.destroyed();
// Clear references
this.#element = null;
this.#props = null;
this.#state = null;
}
// Static registry methods
static register(name, ComponentClass) {
this.#registry.set(name, ComponentClass);
}
static create(name, element, props) {
const ComponentClass = this.#registry.get(name);
if (!ComponentClass) {
throw new Error(`Component '${name}' not found in registry`);
}
return new ComponentClass(element, props);
}
static addGlobalMixin(mixin) {
this.#globalMixins.push(mixin);
}
// Auto-initialization from DOM
static initializeFromDOM() {
document.querySelectorAll('[data-component]').forEach(element => {
const componentName = element.dataset.component;
const props = element.dataset.props ? JSON.parse(element.dataset.props) : {};
try {
this.create(componentName, element, props);
} catch (error) {
console.error(`Failed to initialize component '${componentName}':`, error);
}
});
}
}
// Advanced Form Component Example
class AdvancedFormComponent extends Component {
created() {
this.validators = new Map();
this.errors = new Map();
this.validationRules = this.getProps().validationRules || {};
this.setupValidation();
}
mounted() {
// Set up form event listeners
this.on('submit', this.handleSubmit.bind(this));
this.on('blur', this.handleFieldBlur.bind(this), true); // blur does not bubble: use capture
}
handleFieldBlur(event) {
if (event.target.matches('[data-validate]')) {
this.validateField(event.target);
}
}
setupValidation() {
// Register built-in validators
this.registerValidator('required', (value) => {
return value != null && value !== '';
});
this.registerValidator('email', (value) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return !value || emailRegex.test(value);
});
this.registerValidator('minLength', (value, min) => {
return !value || value.length >= min;
});
this.registerValidator('maxLength', (value, max) => {
return !value || value.length <= max;
});
this.registerValidator('pattern', (value, pattern) => {
const regex = new RegExp(pattern);
return !value || regex.test(value);
});
}
registerValidator(name, validatorFn) {
this.validators.set(name, validatorFn);
}
async handleSubmit(event) {
event.preventDefault();
const isValid = await this.validateAll();
if (isValid) {
const formData = this.getFormData();
try {
await this.submitForm(formData);
this.emit('form:success', { data: formData });
} catch (error) {
this.emit('form:error', { error });
this.showFormError('Submission failed. Please try again.');
}
} else {
this.emit('form:invalid', { errors: this.errors });
this.$('.error')?.focus();
}
}
showFormError(message) {
let banner = this.$('.form-error');
if (!banner) {
banner = document.createElement('div');
banner.className = 'form-error';
this.element.prepend(banner);
}
banner.textContent = message;
}
async validateAll() {
const fields = this.$$('[data-validate]');
const validationPromises = fields.map(field => this.validateField(field));
await Promise.all(validationPromises);
return this.errors.size === 0;
}
async validateField(field) {
const value = field.value;
const rules = field.dataset.validate.split('|');
const fieldName = field.name || field.id;
// Clear previous errors
this.clearFieldError(fieldName);
for (const rule of rules) {
const [ruleName, ...params] = rule.split(':');
const validator = this.validators.get(ruleName);
if (!validator) {
console.warn(`Validator '${ruleName}' not found`);
continue;
}
const isValid = await validator(value, ...params);
if (!isValid) {
const errorMessage = this.getErrorMessage(fieldName, ruleName, params);
this.setFieldError(fieldName, errorMessage);
this.showFieldError(field, errorMessage);
break;
}
}
}
getFormData() {
const formData = new FormData(this.element);
const data = {};
for (const [key, value] of formData.entries()) {
// Handle multiple values (checkboxes, multi-select)
if (data[key]) {
if (Array.isArray(data[key])) {
data[key].push(value);
} else {
data[key] = [data[key], value];
}
} else {
data[key] = value;
}
}
return data;
}
// Create a record through the Web API; the client adds the request verification token
async submitForm(data) {
const { apiClient, entitySet } = this.getProps();
if (!apiClient || !entitySet) {
throw new Error('apiClient and entitySet props are required');
}
return apiClient.post(entitySet, data);
}
setFieldError(fieldName, message) {
this.errors.set(fieldName, message);
}
clearFieldError(fieldName) {
this.errors.delete(fieldName);
}
showFieldError(field, message) {
// Remove existing error display
const existingError = field.parentNode.querySelector('.field-error');
if (existingError) {
existingError.remove();
}
// Create error element
const errorElement = document.createElement('div');
errorElement.className = 'field-error';
errorElement.textContent = message;
// Insert after field
field.parentNode.insertBefore(errorElement, field.nextSibling);
// Add error class to field
field.classList.add('error');
}
getErrorMessage(fieldName, ruleName, params) {
const messages = {
required: `${fieldName} is required`,
email: `Please enter a valid email address`,
minLength: `${fieldName} must be at least ${params[0]} characters`,
maxLength: `${fieldName} must not exceed ${params[0]} characters`,
pattern: `${fieldName} format is invalid`
};
return messages[ruleName] || `${fieldName} is invalid`;
}
}
// Register components
Component.register('advanced-form', AdvancedFormComponent);
What this looks like in practice
A data management interface using all of the above:
// Power Pages data manager built from the pieces above
class PowerPagesDataManager {
constructor(config = {}) {
this.config = {
apiEndpoint: '/_api',
entitySet: 'contacts',
select: ['contactid', 'fullname', 'emailaddress1'],
pageSize: 25,
...config
};
this.apiClient = new APIClient({ baseURL: this.config.apiEndpoint });
this.asyncController = new AsyncController();
this.events = new EventTarget();
this.initialize();
}
async initialize() {
try {
this.initializeComponents();
await this.loadInitialData();
} catch (error) {
console.error('Initialization failed:', error);
}
}
initializeComponents() {
document.querySelectorAll('.advanced-form').forEach(formElement => {
const form = Component.create('advanced-form', formElement, {
apiClient: this.apiClient,
entitySet: this.config.entitySet
});
form.on('form:success', () => this.loadInitialData());
});
}
async loadInitialData() {
const records = await this.asyncController.execute(
'loadInitialData',
() => this.apiClient.get(this.query(), { cache: true }),
{ priority: 'high', cancelPrevious: true }
);
this.emit('data:loaded', { records: records.value });
}
query() {
const params = new URLSearchParams({
'$select': this.config.select.join(','),
'$top': String(this.config.pageSize)
});
return `${this.config.entitySet}?${params}`;
}
async createRecord(recordData) {
const result = await this.run('create', () =>
this.apiClient.post(this.config.entitySet, recordData));
this.emit('data:created', { record: result });
return result;
}
async updateRecord(recordId, updates) {
const result = await this.run(`update_${recordId}`, () =>
this.apiClient.patch(`${this.config.entitySet}(${recordId})`, updates),
{ cancelPrevious: true }); // Cancel any pending update for this record
this.emit('data:updated', { recordId });
return result;
}
async deleteRecord(recordId) {
await this.run(`delete_${recordId}`, () =>
this.apiClient.delete(`${this.config.entitySet}(${recordId})`));
this.emit('data:deleted', { recordId });
}
async run(operationId, operation, options = {}) {
try {
const result = await this.asyncController.execute(operationId, operation, {
priority: 'high',
...options
});
this.apiClient.clearCache();
return result;
} catch (error) {
this.emit('data:error', { operationId, error });
throw error;
}
}
emit(name, detail) {
this.events.dispatchEvent(new CustomEvent(name, { detail }));
}
on(name, handler) {
this.events.addEventListener(name, event => handler(event.detail));
}
}
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
window.dataManager = new PowerPagesDataManager({ entitySet: 'contacts' });
window.dataManager.on('data:loaded', ({ records }) => {
console.log(`${records.length} contacts loaded`);
});
});
The contacts entity set has to be enabled for the Web API in site settings, with the columns listed, and the signed-in user’s web role needs table permissions for it. Real-time updates and a data table component are left out; both are worth their own post.
How to make a mess and fix it
- Memory leaks - clean up, and use WeakMap/WeakSet for object references you don’t own
- Race conditions - cancel in-flight operations and queue where order matters
- Event listeners piling up - remove them when a component is destroyed. Always.
- Module dependency tangles - import/export, and watch for circular dependencies
- Slow somewhere - profile before you optimise. Your guess will be wrong.
Five habits worth keeping
- Add types - JSDoc at minimum, TypeScript if you can
- Error boundaries at both component and application level
- Test - unit tests on the utilities, integration tests on the components
- Consistent structure and naming so people can find things
- Document the public API and anything clever enough to need explaining
Wrapping up
Treat portal JavaScript like real software and it stays workable. Modular architecture, sane async patterns, honest error handling, and enough testing that you can change something without holding your breath.
A note on production: use environment promotion, automate the tests in your pipeline, keep a rollback that you’ve tried, and document what you customised and why. Structured logging with correlation IDs will save you hours the first time something breaks in production.
Useful links
- Developer capabilities overview
- Add custom JavaScript to a page
- Client API: server endpoints and cloud flows
- Web API overview
- Web API write, update and delete operations
- Manage your site’s Content Security Policy
Next: custom API development, and connecting the portal to everything else.