Skip to content

Instantly share code, notes, and snippets.

@bschaeffer
Last active December 20, 2015 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bschaeffer/6140196 to your computer and use it in GitHub Desktop.
Save bschaeffer/6140196 to your computer and use it in GitHub Desktop.
Always resolve a deferred object. This came in handy for me when entering an Ember application on an invalid route.
# Always resolve a Deferred object. Expects that the given method
# will return a Deferred object.
#
App.resolveAlways = (method) ->
deferred = jQuery.Deferred()
method().then (resolved) ->
deferred.resolve(resolved)
, (rejected) ->
deferred.resolve(rejected)
deferred.promise()
/**
* Always resolve a Deferred object. Expects that the given method
* will return a Deferred object.
*/
App.resolveAlways = function(method) {
var deferred = jQuery.Deferred();
method().then(function(resolved) {
deferred.resolve(resolved);
}, function(rejected) {
deferred.resolve(rejected);
});
return deferred.promise();
}

Resolve all the routes

Take an Ember.js router like so:

App.Router.map ->
  @route 'login'
  @route 'account', path: '/:handle'

App.AccountRoute = Ember.Route.extend
  model: (params) ->
    App.Account.findByHandle(params.handle)
  
  serialize: (model) ->
    {handle: model.get('handle')}

Assuming the handle bschaeffer exists, entering the application at app.com/bschaeffer will find the Account and load the template for the route into the application template. However, entering the application at app.com/invalid_handle will cause the model to be rejected and prevent from Ember from rendering the application template, in turn preventing you from rendering a "Not Found" message into the application template. I did't like this because I wanted the application template to be there, so heres how we handle that:

App.AccountRoute = Ember.Route.extend
  model: (params) ->
    App.resolveAlways ->
      App.Account.findByHandle(params.handle)

  renderTemplate: (controller, account) ->
    if customIsErrorChecker(account)
      # Render a 404 page
      @render('notFound')
    else
      # Business as usual
      @_super()

Notes

  • Entering a route means loading the application for the first time at the given route.
  • If you don't care about having the application template, none of this matters.
  • You can render the application template in an error event handler, but that won't work if you try to re-render the application template again after some successful route states.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment