PDA

View Full Version : Defining functions that can be used anywhere



rTankersley
13 Jan 2012, 5:02 PM
Hey all,

I've never been able to figure out how to make a function that I can use anywhere in MVC architecture. For example, say I want to be able to load something into the middle panel, and I can take three different paths to reach that panel (i.e. clicking a button, diving into a grid and using a search box. Note: that's just a general example). I want to perform the exact same thing every time, but because I have to listen for click events on different objects, I have to three copies of the code. If I change one, I have to change it two other times.

Now, I could just point the click events to the same function, but if I have multiple controllers (which I do), that doesn't work. So my question, is there a way that I can define sort of a global function that I can use anywhere? A function that 3 different event handlers in 3 different controllers can all call doThis();.

Thank you for your help.

slemmon
13 Jan 2012, 7:31 PM
You might set up the method in your application:


Ext.application (http://docs.sencha.com/ext-js/4-0/#!/api/Ext-method-application)({
name:'MyApp',
launch:function(){
Ext.create (http://docs.sencha.com/ext-js/4-0/#!/api/Ext-method-create)('Ext.container.Viewport (http://docs.sencha.com/ext-js/4-0/#!/api/Ext.container.Viewport)',{
items:{
html:'My App'
}
});
},
myGlobalFunction: function () {
// WHAT YOU WANT THE GLOBAL APP TO DO
}
});

and in your controller you can listen to and respond to the event:


Ext.define('MyApp.controller.MyControllerA', {
extend: 'Ext.app.Controller',


init: function() {
this.control({
'myGrid': {
render: this.app.myGlobalFunction
}
})
}
});


and each separate controller could refer to the same app.myGlobalFunction

rTankersley
13 Jan 2012, 10:44 PM
Thanks! I appreciate your response.

basememara
11 Feb 2012, 2:34 AM
How would I get the app's reference when not in a controller. I am trying to call the app's global function from a store's load listener.

slemmon
11 Feb 2012, 1:29 PM
This is from something I saw mitchellsimmons do:



Ext.application (http://docs.sencha.com/ext-js/4-0/#!/api/Ext-method-application)({ name:'MyApp', launch:function(){ me.app = me; Ext.create (http://docs.sencha.com/ext-js/4-0/#!/api/Ext-method-create)('Ext.container.Viewport (http://docs.sencha.com/ext-js/4-0/#!/api/Ext.container.Viewport)',{ items:{ html:'My App' } }); }, myGlobalFunction: function () { // WHAT YOU WANT THE GLOBAL APP TO DO }});

Now from anywhere you can reference the app using MyApp.app.