Last time we looked at how we can use ExtJS 4.x’s MVC architecture to gain all the benefits of clean and well organises code base without having to use a full “single page app” viewport style methodology.

As you may remember, this can come in handy in your web application if you’re not using the ExtJS framework exclusively or if you’re just opting for a more traditional build with ExtJS providing supporting components to enhance your HTML.

This time we’re going to take a very quick look at one of the problems you may encounter when you have a set up like this; how to call an ExtJS controller method from not only another controller but even from outside the ExtJS namespace entirely.

As you may remember from before, we had our application definition (to which I’ve now added a new method – sayHi:


Ext.application({
 name: 'MyApp',
 controllers : [
  'MyController'
 ],
 sayHi : function ( name ) {
  alert( name ? 'Hi ' + name + ', how are you?' : 'Hi.....sorry, what was your name?' );
 }
});

And a controller definition:


Ext.define('MyApp.controller.MyController', {
 extend: 'Ext.app.Controller',
 init: function() {
  this.control({
   'button': {
    click: this.onAnyButtonClick
   }
  });
 },
 onAnyButtonClick : function ( b ) {
  console.log('a button was clicked');
 },
 onSomeOtherThing : function() {
  alert ('some other thing');
 }
});

But how do we call the sayHi method from outside the ExtJS namespace? Bearing in mind this is an ExtJS 4.1.x example (things improve slightly in 4.2.x but I’ll write about that in a future update), the way I go about doing it is as follows:


var App = {};

Ext.application({
 name: 'MyApp',
 controllers : [
  'MyController'
 ],
 sayHi : function ( name ) {
  alert( name ? 'Hi ' + name + ', how are you?' : 'Hi.....sorry, what was your name?' );
 },
 init : function() {
  // by assigning 'this' to App.MyApp we have a relatively nicely namespaced global variable we can reference elsewhere 
  App.MyApp = this;
 } 
});

You can now call that application level method from anywhere in your code base:


App.MyApp.calledFromOutside ('Alfonso')     // will alert 'Hi Alphonso, how are you?'

Next time we will take a look at controller methods and how we can call them from other controllers and from outside the ExtJS namespace.

  • Rahul Roy

    Hi this is nice. I myself needed to call a controller method from an external js file, & found this to be the easiest way to do it. Thanks. Is it safe though? What do you think?

    • therealjamesg

      Yes I’d say it’s safe enough. I use it in a production environment without issue.