google / google/material-design-lite

Documentation of .mdlDowngrade_ method in wiki is vague + possible bug in 1.1.3 regarding the "mdl-componentdowngraded" event

Open
#4,209 23 comments 0 reactions 0 assignees View on GitHub
Component Handler Documentation
Dominant language
HTML
Stars
32.2k
Forks
4.9k
PR merge metrics
No merged PRs in 30d

Description

Component (if any):

What are you trying to do or find out more about?
Clean up the component if it needs to be removed.

Where have you looked?
https://github.com/google/material-design-lite/wiki/Making-your-first-JS-component

Where did you expect to find this information?
https://github.com/google/material-design-lite/wiki/Making-your-first-JS-component

From wiki:
"Since this component adds an event listener to the element the mdlDowngrade_ method should be implemented to clean up the component if it needs to be removed."

``` javascript
Dropdown.prototype.mdlDowngrade_ = function() {
'use strict';
this.element_.removeEventListener('click', this.boundClickHandler);
};
```

If you don't add a listener to the **mdl-componentdowngraded** event in the component's `init` method, the `mdlDowngrade_` method will not be called. So the `init` method should have code similar to this - I think.

``` javascript
Dropdown.prototype.init = function() {
"use strict";
this.boundClickHandler = this.clickHandler.bind(this);
this.element_.addEventListener('click', this.boundClickHandler);

this.element_.addEventListener('mdl-componentdowngraded', this.mdlDowngrade_.bind(this.element_));
};
```

And in mdlDowngrade_

``` javascript
Dropdown.prototype.mdlDowngrade_ = function() {
'use strict';
this.element_.removeEventListener('click', this.boundClickHandler);
this.element_.removeEventListener('mdl-componentdowngraded', this);
this.classList.remove(IS_UPGRADED);
};
```

A (pseudo) test

``` javascript
it('downgrades successfully', () => {

// Code to insert component via insertAdjacentHTML
........

// Upgrade
const element = document.querySelector('#my-dropdown');
componentHandler.upgradeElement(element, 'Dropdown');

// Downgrade
componentHandler.downgradeElements(element);
expect(element.getAttribute('data-upgraded')).to.not.include('Dropdown');
});
```

Regards
Leif Olsen

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.