Adding Callbacks to your Sencha Touch Controllers

Short and sweet. I needed a callback in several of my controllers to validate that a user is logged in, and if not redirect them back to the login screen. My file structure for this project looks a lot like Rails, so I have a config/initializers directory, and in that I’ve dumped a controllers.js file which contains the following:


Ext.Dispatcher.on('before-dispatch', function(interaction) {
  if(Ext.isFunction(interaction.controller.beforeFilter)) {
    return interaction.controller.beforeFilter.call();
  };
  return true;
});

Ext.Dispatcher.on('dispatch', function(interaction) {
  if(Ext.isFunction(interaction.controller.afterFilter)) {
    return interaction.controller.afterFilter.call();
  };
  return true;
});

In my application setup, I have a function (requireUser) that handles my logic for requiring that a user be logged in:


Ext.regApplication({
  // code, code, code...
  loggedIn: readCookie('user_credentials') || false,
  requireUser: function() {
    if(app.loggedIn) return true;
    app.flash.warning = 'Please login to continue.';
    Ext.redirect('login');
    return false;
  },
  flash: {
    notice: '',
    warning: ''
  }
});

Then in each of the files I want to require a user (or run some other before/after filter logic) I have something like so…


Ext.regController('accounts', {
  beforeFilter: app.requireUser,
  model: 'Account',
  index: function(options) {
    app.views.viewport.setActiveItem(
      app.views.accountsList, options.animation
    );
  },
  // other actions here...
});

For reference on Ext.Controller and Ext.Dispatcher, check out the Sencha Touch docs

Since it is Sencha on Rails, I feel like this approach adds a nice, seamless integration. Feel free to use, share, comment at will. Happy coding! :)

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

This entry was posted in Development, Sencha Touch. Bookmark the permalink.

3 Responses to Adding Callbacks to your Sencha Touch Controllers

  1. Romy says:

    thanks for posting this! you RULE!

  2. alex says:

    great job, exactly what i’m looking for!
    thank you very much!

  3. Eddie says:

    Brilliant that’s just what I was after too. Nice way to handle user access.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>