CreativeIT / getmdl-select

Select for material-design-lite
http://creativeit.github.io/getmdl-select/
MIT License
301 stars 87 forks source link

Add the ability to remove event listeners #77

Open naftasantos opened 6 years ago

naftasantos commented 6 years ago

I have a screen with dynamically loaded html content. In one of these contents, I use the MDL select component. However, sometimes I need to destroy this screen and build another one that does not have this component.

This behavior causes some crashes inside getmdl-select.js hideAllMenus, because the necessary objects do not really exist anymore. More specifically in the line 63: menu['MaterialMenu'].hide();.

image

I did some debug, and realized that the problem was occurring because on line 68, there is an event listener being added to the body of the document: document.body.addEventListener('click', hideAllMenus, false);

Since this event listener uses a named function declared inside the function _addEventListeners, I can't remove it from outside of the function. Also, every time I load a screen that needs to call getmdlSelect.init, a new listener will be added to the body. So, when an event occurs, this function will be called various times.

Similar to getmdlSelect.init('#target'); the component should have a getmdlSelect.dispose('#target'); to allow for a more dynamic usage.

randrianov commented 6 years ago

@naftasantos thank you for sharing, would you like to create PR? it will be very helpful or we will include this into dev plan.

naftasantos commented 6 years ago

I tried to push at least an 'undefined' verification as a quick fix measure, but I have no access. For the full feature, since I changed our project to use another library, I won't be able to work on it. 😄

CragVFX commented 5 years ago

Is there any plan to address this issue? I have the same use-case, of dynamically loaded content. Below is a quick "fix" for the issue, but doesn't resolve the cause.

                [].forEach.call(menus, function (menu) {
                    if (typeof menu['MaterialMenu'] !== 'undefined') menu['MaterialMenu'].hide();
                });