Architect 2 Sencha Docs

Events and Controllers: Adding Interactivity

Most applications that you create are interactive, meaning that they respond to actions taken by the user within the user interface. Some examples of this interactivity are the user clicking a button, selecting an item from a menu, or typing text into a form field. In all these cases, the application must be able to do two things:

  1. Detect when the user has taken a certain action to a view
  2. Execute some code when that happens

Remember that a basic tenet of the MVC architecture is that all logic is in the controllers or helper classes. The View components only render the GUI; the stores, models, and proxies only import and store the data.

In Ext JS and Sencha Touch applications, there are two methods for handling this type of interactivity:

  • event bindings
  • controller actions

Both approaches have distinct advantages, so it’s important to know when to use one versus the other. This guide discusses how to use each method within Architect and how to choose which one to use.

The completed example projects built in this guide can be found in the ExtSimpleExamples Git repository.

Let's start off by addressing the question: Why would you use one method of providing interactivity over the other, even though both methods generate somewhat similar code (as we'll show below).

Event bindings versus controller actions

Architect fully embraces the MVC paradigm for building applications, as it facilitates and encourages an elegant decoupled architecture. Therefore, in just about all cases we recommend using a controller action, for binding to view component events rather than a basic event binding.

The key difference is the following:

  • Controller actions: If you implement behavior that interacts with other components that are not in the top-level class in a project, which is typical for most cases of building applications using Architect, then it generally belongs in a controller.

  • Event handlers: If you implement behavior that interacts with components that are all children of "me" (this) then it generally belongs in an event handler. Put another way, the only time it is acceptable to use a basic event binding is when the event and its handler code are entirely self-contained within a single view and do not rely upon or affect any of the application’s other views, models, or controllers. In other words, use a basic event binding when an event triggered by a view only affects that same view. The simple event binding shown next is actually a good example of this; the button only affects the size of its parent panel and does not touch any other part of the application.

Using an event binding

An event binding, also referred to as an event listener, listens for a particular event to be fired by a user taking action on a component in one of your application’s views, and then invokes a method function of that view. The function is passed a certain set of parameters specific to the type of event that was fired/user action taken.

Let’s look at a very simple example. Say you want a panel to change size when the user toggles a button.

  1. Create an Ext JS 4.1 project.
  2. Add a Panel to the Canvas.
  3. Add a Button as a child of the Panel, and set the Button’s enableToggle config to on.
  4. Add an event binding to the button by clicking the “+” icon next to the Event Bindings item in the Config panel.
  5. Set the Event Binding name config to toggle. Note that Architect automatically gives the binding a function name (fn) of “onButtonToggle”, but you can change that to a whatever name you want.

At this point, you have created a button with an event binding that says, when the button is toggled the app calls the onButtonToggle method. The method is called with three parameters: a reference to the button component, whether it is currently pressed or unpressed, and any extra options specified on the event binding.

Now we need to add the code to perform the desired action of changing the panel’s size. Find the event binding in the Inspector (currently labeled toggle *onButtonToggle*) and double-click it to open the code editor. Architect displays the names of the handler's parameters at the top of the editor. Insert the following code:

if (pressed) {
    this.setSize(100, 200);
} else {
    this.setSize(400, 250);
}

Save and preview the project and click the button; you will see the panel’s size toggle from one size to the other.

Let’s examine the code that Architect generates to do this:

Ext.define('MyApp.view.MyPanel', {
    extend: 'Ext.panel.Panel',

    height: 250,
    width: 400,
    title: 'My Panel',

    initComponent: function() {
        var me = this;

        Ext.applyIf(me, {
            items: [
                {
                    xtype: 'button',
                    enableToggle: true,
                    text: 'MyButton',
                    listeners: {
                        toggle: {
                            fn: me.onButtonToggle,
                            scope: me
                        }
                    }
                }
            ]
        });

        me.callParent(arguments);
    },

    onButtonToggle: function(button, pressed, options) {
        if (pressed) {
            this.setSize(100, 200);
        } else {
            this.setSize(400, 250);
        }
    }
});

You can see that it adds a listener for the toggle event on the button component, telling it to call the onButtonToggle method that contains our handler code.

Also note that the listener is set up to execute within the scope of the me variable, which refers to the top-level Panel instance. Architect always sets up event bindings to execute in the scope of the top-level View component in which they are defined. This guarantees that the this keyword within the handler code always refers to the object on which the handler method is defined (not the one to which the event binding was added). This is also why the this.setSize() calls in the example handler code changes the size of the panel and not the button.

Event bindings can also be added to things that are not view components, such as data stores or anything else that is observable.

Note You cannot hard-code your own listener in Architect.

Using a controller

A critical part of Sencha’s MVC architecture, a controller provides the glue that lets your application’s various models and views work together without having to specifically know about one another. This helps maintain strict decoupling of the parts of your application and keep each individual view completely self-contained. This leads to a more robust, modular, maintainable application.

See the Controllers Reference for details about available configuration options for controllers.

Much like event bindings, controller actions let your application listen to a specific named event on a particular view component and execute handler code. A controller action is defined as part of the controller -- instead of being defined as part of a specific target component. As a result, you have to tell the controller action what component (or components) it should listen to. This is done by specifying a controlQuery for the action, which is a ComponentQuery selector that selects the appropriate target component(s).

Let’s recreate our event binding example using a controller action.

  1. Add a Panel to the Canvas, then add a Button to the Panel with its enableToggle config switched on.
  2. Set the Button itemId config to sizeToggle, which we use later.
  3. Add a Controller to the application using the Add button ("+") in the Inspector.
  4. Add a Controller Action as a child of that controller through the Config panel. When prompted, select Ext.button.Button as its target type (which sets the action's targetType config), then toggle for its event (the action's name config). This combination of targetType and name lets Architect look up the correct parameters for the event handler.)
  5. Next, set the Controller Action controlQuery config so the controller knows how to target our button. There are many possible queries that will work, but for this example we will use a query based on the Button itemId set earlier. Set controlQuery to button#sizeToggle. The “#” indicates an id/itemId query.

Finally add the handler code. Double click the controller action (named toggle onButtonToggle in the Inspector) to open the code editor, and add the following code:

var panel = button.up('panel');
if (pressed) {
    panel.setSize(100, 200);
} else {
    panel.setSize(400, 250);
}

This code is slightly different than the event binding version. Since the controller handler is executed in the scope of the controller instead of the panel, we cannot use the “this” keyword and instead we have to explicitly get a reference to the panel.

Save and preview your project and you will see that once again clicking the button toggles the panel’s size.

Here's the code generated by Architect for the controller:

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

    onButtonToggle: function(button, pressed, options) {
        var panel = button.up('panel');
        if (pressed) {
            panel.setSize(100, 200);
        } else {
            panel.setSize(400, 250);
        }
    },

    init: function(application) {
        this.control({
            "button#sizeToggle": {
                toggle: this.onButtonToggle
            }
        });
    }
});

This looks similar to the code generated for the event binding, the main difference being that the listener is set up by calling this.control() with the controlQuery as a key.

Converting an event binding to a controller action

If you've used a simple event binding and decide that you need to change that to a controller action, Architect gives you an easy way to do that. Right-click the event binding in the Inspector, highlight "Convert to Action >", and either choose an existing controller or "New Controller" to tell Architect where to put the new controller action. Architect prepopulates the controller action's name config and handler code with the values from the original event binding. You have to manually fill in the controlQuery config.