From ef69a4a666b8335f52ecc09d88f86d09da24c67b Mon Sep 17 00:00:00 2001 From: Zander Otavka Date: Fri, 23 Sep 2016 12:53:42 -0500 Subject: [PATCH] Prevent component upgrades by catching events. --- src/mdlComponentHandler.js | 50 +++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/src/mdlComponentHandler.js b/src/mdlComponentHandler.js index e4e652395..f532a9887 100644 --- a/src/mdlComponentHandler.js +++ b/src/mdlComponentHandler.js @@ -141,6 +141,27 @@ componentHandler = (function() { return upgradedList.indexOf(jsClass) !== -1; } + /** + * Create an event object. + * + * @param {string} eventType The type name of the event. + * @param {boolean} bubbles Whether the event should bubble up the DOM. + * @param {boolean} cancelable Whether the event can be canceled. + * @returns {!Event} + */ + function createEvent_(eventType, bubbles, cancelable) { + if ('CustomEvent' in window && typeof window.CustomEvent === 'function') { + return new CustomEvent(eventType, { + bubbles: bubbles, + cancelable: cancelable + }); + } else { + var ev = document.createEvent('Events'); + ev.initEvent(eventType, bubbles, cancelable); + return ev; + } + } + /** * Searches existing DOM for elements of our component type and upgrades them * if they have not already been upgraded. @@ -185,6 +206,13 @@ componentHandler = (function() { if (!(typeof element === 'object' && element instanceof Element)) { throw new Error('Invalid argument provided to upgrade MDL element.'); } + // Allow upgrade to be canceled by canceling emitted event. + var upgradingEv = createEvent_('mdl-componentupgrading', true, true); + element.dispatchEvent(upgradingEv); + if (upgradingEv.defaultPrevented) { + return; + } + var upgradedList = getUpgradedListOfElement_(element); var classesToUpgrade = []; // If jsClass is not provided scan the registered components to find the @@ -227,16 +255,8 @@ componentHandler = (function() { 'Unable to find a registered component for the given class.'); } - var ev; - if ('CustomEvent' in window && typeof window.CustomEvent === 'function') { - ev = new CustomEvent('mdl-componentupgraded', { - bubbles: true, cancelable: false - }); - } else { - ev = document.createEvent('Events'); - ev.initEvent('mdl-componentupgraded', true, true); - } - element.dispatchEvent(ev); + var upgradedEv = createEvent_('mdl-componentupgraded', true, false); + element.dispatchEvent(upgradedEv); } } @@ -358,15 +378,7 @@ componentHandler = (function() { upgrades.splice(componentPlace, 1); component.element_.setAttribute('data-upgraded', upgrades.join(',')); - var ev; - if ('CustomEvent' in window && typeof window.CustomEvent === 'function') { - ev = new CustomEvent('mdl-componentdowngraded', { - bubbles: true, cancelable: false - }); - } else { - ev = document.createEvent('Events'); - ev.initEvent('mdl-componentdowngraded', true, true); - } + var ev = createEvent_('mdl-componentdowngraded', true, false); component.element_.dispatchEvent(ev); } }