UNPKG

@peterwidmer/form-store

Version:

reactive store for dynamics 365 forms

91 lines (89 loc) 3.48 kB
function CreateStore(eventContext) { const handlers = {}; const dataStorage = {}; const attachedAttributes = []; let self; const store = { setValue: (property, value) => { var propertyContext = { previousValue: dataStorage[property], changedProperty: property }; dataStorage[property] = value; if (handlers[property]) { handlers[property].forEach(h => h(self, propertyContext)); } }, getValue: (property) => { if (dataStorage[property] != undefined) { return dataStorage[property]; } return null; }, register: (callback, crmFields, otherProperties = null) => { if (crmFields) { crmFields.forEach((field) => { if (!attachedAttributes.includes(field)) { const crmAttribute = eventContext.getFormContext().getAttribute(field); if (!crmAttribute) { return; } dataStorage[field] = crmAttribute.getValue(); const onChange = () => { const propertyContext = { previousValue: dataStorage[field], changedProperty: field }; const crmAttribute = eventContext.getFormContext().getAttribute(field); dataStorage[field] = crmAttribute.getValue(); if (handlers[field]) { handlers[field].forEach(h => h(self, propertyContext)); } }; crmAttribute.addOnChange(onChange); attachedAttributes.push(field); } const list = handlers[field] ?? []; if (!list.includes(callback)) { list.push(callback); } handlers[field] = list; }); } if (otherProperties) { otherProperties.forEach((property) => { const list = handlers[property] ?? []; list.push(callback); handlers[property] = list; }); } }, unsubscribe: (event, callback) => { let list = handlers[event] ?? []; list = list.filter(h => h !== callback); handlers[event] = list; }, getEventContext: () => { return eventContext; }, getFormContext: () => { return eventContext.getFormContext(); }, getContextEntityName: () => { return eventContext.getFormContext().data.entity.getEntityName(); }, completeRegistration: () => { const allRegisteredCallbacks = []; for (const key in handlers) { handlers[key].forEach((callback) => { if (!allRegisteredCallbacks.includes(callback)) { allRegisteredCallbacks.push(callback); } }); } allRegisteredCallbacks.forEach(callback => { callback(self); }); }, init: (store) => { self = store; return self; } }; return store.init(store); } export { CreateStore };