this.mon(toolsUl, 'click', this.onClick, this);
Looks like event handler installation but what it really does anyway?
So I delved into the code and remembered ExtJS Conference and now it is clear to me.
Imagine you create a component and then you need to install an event handler, for example, on its body. Something like:
var handler = function() { alert('You clicked my body'); }; var p = new Ext.Panel({ renderTo:Ext.getBody() ,title:'Panel with a listener on the body' }); p.body.on('click', handler);
Easy enough, we’ve done something like this many times. But, if the panel is ever to be destroyed we need to remove this listener ourselves as Ext knows nothing about it.
Something like:
var p = new Ext.Panel({ renderTo:Ext.getBody() ,title:'Panel with a listener on the body' ,beforeDestroy:function() { this.body.un('click', handler); } });
If we install our listener as inline function, such as:
p.on('click', function() {alert('You clicked my body')});
then it is impossible to remove this listener selectively, you would need to use
p.body.removeAllListeners();
to remove all body listeners.
Now, if we use mon
(m stands for “managed”) this way
p.mon(p.body, 'click', handler);
then the listener is automatically removed by Ext on panel destroy. Nice, isn’t it? Saves a lot of our work and also handles our laziness or forgetfulness about destroying and cleanups of components.
Mind the first argument, that is the element to install the listener to. It can, but not necessarily have to be within the component. Also remember that when you destroy p
Ext only removes listener from the element so if the element is outside of p
you need to remove it yourself if it is not necessary anymore.
Should you ever need to remove the listener installed by mon
you use mun
with same arguments. You cannot selectively remove inline listeners.
mon
and mun
are defined in Component so you can use them from Component down the descendant classes chain.
Warning! mon
and mun
are not documented (yet?) so there is still (a little) risk that they will change or will be removed.
- Ext, Angular, React, and Vue - 27. June 2019
- The Site Resurgence - 11. February 2018
- Configuring ViewModel Hierarchy - 19. June 2015
7 Responses
@Ed Spencer,
mun would be used if you want to remove one listener before the component is destroyed. All listeners are removed automatically when component is destroyed.
Anyway, yes, I’d expect mun won’t be used that often.
@Thorsten, I also think that risk is low, still, should be documented.
Saki, the “mon()” method was introduced in the “Ext 3.0” blog post, so I assume there’s not much risk in using, except for API changes _maybe_. See http://www.extjs.com/blog/2009/08/10/ext-js-30-be-outstanding/ – “Memory Management Improvements”.
Another fine piece of information from the ExtJS Guru. Thanks Saki !!
🙂
Presumably the use of mun is pretty rare if handlers are removed for us?
Great reading Saki! 🙂
fyi M = Managed