Skip to content

Commit

Permalink
Prevent component upgrades by catching events.
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexanderOtavka committed Sep 23, 2016
1 parent 2666977 commit ef69a4a
Showing 1 changed file with 31 additions and 19 deletions.
50 changes: 31 additions & 19 deletions src/mdlComponentHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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);
}
}
Expand Down

0 comments on commit ef69a4a

Please sign in to comment.