OMG: ExtJS4 MVC = OSM

WARNING: This post is all JavaScript, ExtJS, and programming… 🙂 very nerdy. You’ve been warned.

I just want to gush a little bit about this new feature in ExtJS 4. The new Model View Controller architecture is a pure joy to work with. Now we can create components that render the various visual elements of the UI and defer the behavior to something else.

Before (in pre-MVC-land), buttons, form elements, and controls emitted events that you wanted to handle. The only problem was that the quickest, and often shortest, route was to make the owning component deal with the events from its children. This often led to very spaghetti-like code, i.e. Panel B wants to react to Menu Item 2’s click. Panel B would have to get a reference to Menu Item 2 and register a click event handler. Sounds simple, but multiply that by several hundred, or thousand, times and it starts to get a bit unruly.

Thankfully, the geniuses at Sencha have come up with a very beautiful solution: The MVC. With the MVC we can just throw up the UI with all its panels, menus, buttons and what have you and then, once it looks awesome, we create the “Controllers” that stitch it all together. The controller can be as simple as this:

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

    views: [ 'AccountForm' ],

    init: function() {
        this.control({
            'account-form button[action]':{
                'click':function(){
                    /*do something when a button with a property action is clicked in the account form*/
                }
            }
        });
    }
});

Check out the full documentation on the MVC here.

Over the last several months, I’ve been building up a new application and doing my best to make it true to the MVC. Though, I have to admit, I jumped in with the ExtJS3 mentality so my first set of components did have ‘controller’ code meshed in them, but as I’ve learned the “new way” I’ve been going back and “fixing” those in order to soar in the MVC. 🙂

Next up: how I setup Unit Testing with Jasmine & the ExtJS MVC.

Enhanced by Zemanta