JSFiddle - React, Tailwind, and code Playground
by Nalin Sajwan
JavaScript
const event = {
detail: {
action: 'PRODUCT_DELETE',
id: '20',
associationId: '50'
}
};
const actionAttributes = event.detail.action;
function deleteProductAssociations(id) {
console.log('deleteProductAssociations ==> ', id);
};
function addProductWithPageToCatalogue(id, associationId) {
console.log('addProductWithPageToCatalogue ==> ', id, associationId);
};
function deleteVariantAssociations(id) {
console.log('deleteVariantAssociations ==> ', id, associationId);
};
function getObjPath(obj, path) {
return path.split('.').reduce((o, i) => {
if (o !== undefined && o[i] !== undefined) return o[i]
else return undefined
}, obj);
};
let actionHandlers = {
'PRODUCT_DELETE': {
handler: deleteProductAssociations,
params: [
'detail.id'
]
},
'PRODUCT_ASSOCIATE': {
handler: addProductWithPageToCatalogue,
params: [
'detail.id',
'detail.associationId'
]
},
'VARIANT_DELETE': {
handler: deleteVariantAssociations,
params: [
'detail.id'
]
}
};
let handlerMatched = actionHandlers[actionAttributes];
let populatedParams = handlerMatched.params.map(key => {
return getObjPath(event, key);
});
console.log('populatedParams ==> ', populatedParams);
handlerMatched.handler.apply(this, populatedParams);