PDA

View Full Version : What is the proper way to create listeners on reusable MVC views?



gnube
22 Nov 2011, 6:45 AM
So far i have been using a few mechanisms for creating listeners in my MVC Views. I want my views to be re-usable as well as be able to have multiple instances created on my page at one time. This means that I want to be sure my listeners are created and removed appropriately.


I have managed to put 95% of my listener code into my controller and have mechanisms to identity the id's of the views responsible for firing events. But there are a few listeners stuck in view configs and plugin configs handling dd events, cell edits and the like.


e.g. from an initComponent()



//Dynamically create the plugin so that is valid for each instantiation
me.plugins = Ext.create('Ext.grid.plugin.TreeCellEditing',
{
clicksToEdit:2
,
listeners: {
edit: function(editor, e) {
if (e.record.dirty){ // save and commit the changes via the controller after editing finished
var newRecord = e.record.copy();
editor.grid.fireEvent('cxAfterCellEdit', editor, e, newRecord); // use the controller to keep data changes centralised
}
}
}
}



Firstly, I don't like that I have used an anonymous function, secondly I suspect that the listeners:{} configuration will not actually create managed listeners which will be destroyed when my control is destroyed.



I have setup managed listeners in views with named functions outside of config descriptions and would like to configure the equivalent listeners in these config items so I feel sure that views can be destroyed cleanly e.g.




me.addManagedListener( me, 'itemcontextmenu',me.doRowCtxMenu);

In my controllers I have used this.control({}) to setup listeners - I can't see the controllers being destroyed for any reason so I am not so concerned about these - from what I can see so far - these are also non-managed???



this.control({
'MyGrid button#refresh' : {
click: me.onGridButtonRefresh
},



How do I setup listeners in these viewConfigs and plugin configs properly so that they are destroyed when the view is destroyed by a tab panel closing or whatever?

mitchellsimoens
22 Nov 2011, 9:56 AM
When you use this.control you aren't actually putting listeners on the view themselves. The view fires an event and the underlying Ext.app.EventBus gets this event and then goes through and finds any selector you specified in this.control and fires the listener. So Ext.app.EventBus is a middle man to the view and the Controller. The only time you have to manage removing listeners is if you use this.on or this.addListener within the view which you shouldn't do if you are using MVC.

gnube
22 Nov 2011, 3:44 PM
Excellent! Thanks Mitchell, nicely explained.