Via EmberFest: Complex Architectures in Ember

Wow! This takes me back! Please check the date this post was authored, as it may no longer be relevant in a modern context.

On Friday I gave a presentation at EmberFest. The talk was framed by having worked on several Ember codebases, including one for almost 9 months. I’ve found that new Ember developers (or even experienced ones!) tend to lean heavily on feature-rich controllers to architect their applications- this works for a time, but as a codebase grows in complexity the controllers become unwieldy and confusing.

The fantastic Luke Melia must be thinking the same thing, because in RC8 he landed a change of the events hash to be called actions. This cosmetic change is almost a distraction from the real change: A refactoring of how controllers, routes, and views handle actions.

There is now an Ember.ActionHandler mixin that unifies the behavior. Check it out:

var Actionable = Ember.Object.extend(Ember.ActionHandler);

var secondTarget = Actionable.extend({
  actions: {
    "Wie Ghet's": function(){
     console.log("Und dir?");
    }
  }
}).create();

var firstTarget = Actionable.extend({
  target: secondTarget,
  actions: {
    "Wie Ghet's": function(){  // If actions was undefined or this action didn't exist, only secondTarget would handle it.
      console.log("Danke gut");
      return true; // If you return true, the event will continue to bubble.
    }
  }
}).create();

firstTarget.send("Wie Ghet's");


// Danke gut
// Und dir?

Having this behavior consistent, especially the logic behind when to bubble an action or not, is incredibly important. Thanks Luke!

I find that most successful Ember projects follow a simple pattern for application design:

  • Controllers present information to templates. And not much else, ideally.
  • Actions are handled on routes. This makes routes (which can access models and arbitrary controllers via controllerFor) and controllers each responsible for a different set of concerns.

The result is better and more maintainable code. Here are the slides from the talk:

Rumor has it that we may have video soon, I’ll update this post when they are published.

Update: Many thanks to Luke Melia for catching a few bugs in the code samples!

Update 2: Now with video from the NYC meetup.