Refreshing a Route


#1

I have a route that fetches some data and then acts on it:

var ContactsRoute = Ember.Route.extend({
  model: function() {
    return App.Contacts.all().fetch();
  },

  setup: function(contacts) {
    if (contacts.any()) {
      this.replaceWith('showContact', contacts.firstObject());
    }
  }
});

The behavior is basically to preselect the first item in the list. That works great. What I’m trying to figure out is how to implement

<button {{action="refreshContacts"}}>Refresh</button>

I could replicate the route’s logic in my controller:

var ContactsController = Em.ArrayController.extend({
  refreshContacts: function() {
    this.get('content').refresh().then(function(contacts) {
      if (contacts.any()) {
        this.router.replaceWith('showContact', contacts.firstObject())
      }
    });
  }
};

Of course, I’d prefer to move the logic to the route:

var ContactsRoute = Em.Route.extend({
  events: {
    refreshAll: function() {
      // ???
    }
  }
});

var ContactsController = Em.ArrayController.extend({
  refreshContacts: function() {
    this.get('router').send('refreshAll');
  }
};

But I can’t figure out what to put in the Route’s event handler. It seems weird to me to manually manage the route lifecycle:

refreshAll: function() {
  this.model().then(this.setup.bind(this));
}

I’m going to miss logic that the router does for me.

Has anyone done anything like this?


#2

I have something similar:

We have a sparse array controller that fetches data from our server as necessary, filling in gaps in the data set as required. To make this work, I don’t use the model hook in the router. Instead, I use a series of controller hooks that observe when it needs to refresh the data set upon entering the route again. I admit that it’s a bit hackneyed, but I’m able to do exactly what I want without having the data refresh needlessly.