Why you should be using History in your ExtJS applications

I’ve been making a few updates to the ExtJS API documents application recently. The actual updates include remembering which tabs you have open and using Ext.History to go between tabs (you can follow the forum post or see a beta version).

That’s not quite ready yet, but what has been made very clear to me is that any ExtJS application with more than one view should be using Ext.History. With History we get urls inside the application itself, we can parse them and dispatch accordingly. For example, I’m using a Rails-like Router, which lets you define an internal url map like this:

map.connect(":controllers/:action/:id");
map.connect(":controllers/:action");

The router knows how to decode urls based on the regular expression-like syntax above, and parse the matches into an object – for example:

#users/new    <= becomes {controller: 'users', action: 'new'}
#users/edit/2 <= becomes {controller: 'users', action: 'edit', id: 2}
#colours      <= becomes {controller: 'colours'}

You can of course define any url matching scheme using the connect() function. I then use a simple Dispatcher, which looks at the decoded parameters. It finds the appropriate controller and calls that action on the controller, passing any other parameters as arguments. For example:

#users/new      <= calls UsersController's "new" action
#colours/edit/2 <= calls ColoursController's "edit" action, with {id: 2} as the argument

And so on. Each controller knows what to do for that action. It’s easy then to say to someone “go to http://myapp.com/admin#users/152/comments” – which will take them straight to the comments that user 152 has written. Compare that with saying: “go to http://myapp.com/admin, then click the List Users tab, then find the user called Joe Bloggs, then double click the bubble icon next to his name”. It’s obvious which approach is better.

You don’t even need to use something as elaborate as a router, just a simple switch statement or some regular expressions would be enough for many applications. Once you’ve got Ext.History setup, you could do something as simple as:

//decodes a url and decides how to dispatch it
dispatch = function(token) {
  switch (token) {
    case "users"    :   displayUsers();   break;
    case "users/new":   displayNewUser(); break;
    case "users/2/edit: editUser(2);      break;
    default:            displayDefault(); break;
  };
};
Ext.History.on('change', dispatch);

//Call dispatch on initial page load as Ext.History's change event is not fired here
Ext.History.init(function() {
  var token = document.location.hash.replace("#", "");
  dispatch(token);
});

Obviously you don’t hard code user IDs like that but it’s easy to see how to roll your own. With just a few lines of code, you’ve decoded a url into a function to call, which can do anything you need it to. All your internal navigation needs to do is call Ext.History.add(“some/new/url”), which will now be picked up by your dispatch code.

It’s important to only route like this for idempotent actions (i.e. actions which display data rather than change it), so that data changing actions are not repeated. This is equivalent to using GET and POST correctly in normal web applications.

When the simplest implementation takes just a few lines of code, what reason could there be not to be using it?

Using Ext.History

Ext.History is a small class that was released with ExtJS 2.2, making it easy to use the browser’s back and forward buttons without breaking your AJAX-only pages.

This can be really useful for any ExtJS application with more than one view, for example a simple app with a grid of Products, which can be double-clicked to reveal an edit form. Ext.History allows the user to click the back button to go back to the grid if they’re on the form, and even forward again from the grid. It does this by appending a token to the end of the url:

http://myurl.com/ (default url for the app)
http://myurl.com/#products (shows the products grid)
http://myurl.com/#products/edit/1 (shows the edit form for product 1)

This is useful, so let’s look at how to set it up. Ext.History requires that a form field and an iframe are present in the document, such as this:

<form id="history-form" class="x-hidden" action="#">
  <div>
    <input id="x-history-field" type="hidden" />
    
  </div>
</form>

The div is just there to make the markup valid. Ext.History uses the iframe to make IE play nice. Generally I don’t like to make any assumptions about what is in the DOM structure so I use Ext to generate these elements:

/**
* Creates the necessary DOM elements required for Ext.History to manage state
* Sets up a listener on Ext.History's change event to fire this.handleHistoryChange
*/
initialiseHistory: function() {
  this.historyForm = Ext.getBody().createChild({
    tag:    'form',
    action: '#',
    cls:    'x-hidden',
    id:     'history-form',
    children: [
      {
        tag: 'div',
        children: [
          {
            tag:  'input',
            id:   Ext.History.fieldId,
            type: 'hidden'
          },
          {
            tag:  'iframe',
            id:   Ext.History.iframeId
          }
        ]
      }
    ]
  });

  //initialize History management
  Ext.History.init();
  Ext.History.on('change', this.handleHistoryChange, this);
}

Ext.History.fieldId and Ext.History.iframeId default to ‘x-history-field’ and ‘x-history-frame’ respectively. Change them before running initialiseHistory if you need to customise them (Ext.History is just a singleton object so you can call Ext.History.fieldId = ‘something-else’).

The main method you’ll be using is Ext.History.add(‘someurl’). This adds a token to the history stack and effectively redirects the browser to http://myurl.com/#someurl. To create something like the grid/form example above, you could write something like this:

Ext.ns('MyApp');

MyApp.Application = function() {
  this.initialiseHistory();

  this.grid = new Ext.grid.GridPanel({
    //set up the grid...
    store: someProductsStore,
    columns: ['some', 'column', 'headers'],

    //this is the important bit - redirects when you double click a row
    listeners: {
      'rowdblclick': {
        handler: function(grid, rowIndex) {
          Ext.History.add("products/edit/" + rowIndex);
        }
      }
    }
  });

  this.form = new Ext.form.FormPanel({
    items: ['some', 'form', 'items'],

    //adds a cancel button which redirects back to the grid
    buttons: [
      {
        text: 'cancel',
        handler: function() {
          Ext.History.add("products");
        }
      }
    ]
  });

//any other app startup processing you need to perform
};

MyApp.Application.prototype = {
  initialiseHistory: function() {
    //as above
  },

  /**
   * @param {String} token The url token which has just been navigated to
   * (e.g. if we just went to http://myurl.com/#someurl, token would be 'someurl')
   */
  handleHistoryChange: function(token) {
    var token = token || "";
    switch(token) {
      case 'products':        this.showProductsGrid();     break;
      case 'products/edit/1': this.showProductEditForm(1); break;
      case '':                //nothing after the #, show a default view
    }
  },

  showProductsGrid: function() {
    //some logic to display the grid, depending on how your app is structured
  },

  showProductEditForm: function(product_id) {
    //displays the product edit form for the given product ID.
  }
};

Ext.onReady(function() {
  var app = new MyApp.Application();
});

So when you visit http://myurl.com/#products, showProductsGrid() will be called automatically, and when you visit http://myurl.com/#products/edit/1, showProductEditForm() will be called with the argument 1. You can write your own logic here to change tab or show a window or whatever it is you do to show a different view to the user.

I’m not suggesting you parse the url token using a giant switch statement like I have above – this is only an example. You could get away with something like that for a very small app but for anything bigger you’ll probably want some kind of a router. That goes a little beyond the scope of this article but it is something I will return to at a later date.

There is also an example of Ext.History available on the Ext samples pages.

%d bloggers like this: