Matt Baker
Matt Baker

Reputation: 3454

Save State Between Route Transitions in EmberJS

Is there an acceptable way to save state between routes in an EmberJS application? For example, I have an Infinite Scroller implemented as an ArrayController with pages of content retrieved from the server as the user scrolls. When the user clicks on one of these results I would like to transition to a dedicated "Details" route.

So far so good, but I would also like them to be able to click "back" on their browser, or a back link on the website to go back to the previous route in the state it was in when they left. What is the best way to accomplish this sort of thing within Ember?

Upvotes: 3

Views: 484

Answers (1)

melc
melc

Reputation: 11671

If you load the model of the ArrayController as you scroll (not from a route callback function as model) , say for a route called pages, then by clicking back after visiting a resource like pages/1 the ArrayController should have the last set model and present the last viewed results.

For example,

http://emberjs.jsbin.com/ElADOdeC/1#/pages

js

App = Ember.Application.create();

App.Router.map(function() {
  this.route('pages');
  this.route('page',{path:'/pages/:page_id'});
});

App.IndexRoute = Ember.Route.extend({
  beforeModel: function() {
    this.transitionTo('pages');
  }
});

App.PagesController = Ember.ArrayController.extend({
  index:0,
  pages:function(){
    return pagesData.slice(this.get('index'),this.get('index')+2);
  }.property('index'),
  actions:{
    next:function(){
      if(this.get('index')==pagesData.length-1){
        this.set('index',0);
      }else{
        this.set('index',this.get('index')+1);
      }
    }
  }
});

App.PageRoute = Ember.Route.extend({
  model:function(params){
    return pagesData[params.page_id];
  }
});

App.Page = Ember.Object.extend({
  id:null,
  pageContent:"This is the content of this page"
});

var pagesData = [];
for(var i=0;i<10;i++){
  pagesData.pushObject(App.Page.create({id:i}));
}

hbs

<script type="text/x-handlebars" data-template-name="index">
    nothing here
  </script>
  <script type="text/x-handlebars" data-template-name="pages">
    Pages
    <br/>
    {{#each page in pages}}
    {{page.id}}
    <br/>
    {{page.pageContent}}
    <br/>
    {{#link-to 'page' page}}details{{/link-to}}
    <br/>
    <hr>
    <br/>
    {{/each}}
    <button {{action "next"}}>next</button>
  </script>
  <script type="text/x-handlebars" data-template-name="page">
    <b>This is page</b> {{id}} <br/>
    <b>with content:</b></br>
    {{pageContent}}
  </script>

Upvotes: 1

Related Questions