Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrapping data in ember.js

What's the best way to bootstrap data for an emberjs app on page load. I know it will most likely get the data from either a data-for attribute or data within a hidden div, but where in the emberjs app lifecycle would this go?

like image 365
spullen Avatar asked Mar 14 '13 20:03

spullen


1 Answers

There are a few different kinds of data that you might be loading. I have been using ember-data models along with DS.FixtureAdapter (for static data) or the DS.RESTAdapter (for dynamic data.

This is a small example using fixtures:

App.Store = DS.Store.extend({
  revision: 11,
  adapter: 'DS.FixtureAdapter'
});

App.Page = DS.Model.extend({
  title: DS.attr('string')
});

App.Page.FIXTURES = [{
    id: 1,
    title: "Test Title #1"
  }, {
    id: 2,
    title: "Random Title #2"
  }];

In my (smallish) apps I am just loading the fixture data directly after defining the store and models. This works well for simple one to one associations (think a static listing of types or categories). When using non fixture type data it is just specified as the model attribute on the route, and is loaded up when needed.

Update

To pre-load initial data (e.g. initial page state like loggedIn) on page load you could use DS.Store#load:

Store = DS.Store.create({
  revision: 11
});

Page = DS.Model.extend({
  title: DS.attr('string')
});

Store.load(Page, {id: 1, title: 'Wow Cool Title'});

Store.find(Page, 1).get('title') //=> 'Wow Cool Title'
like image 173
Robert Jackson Avatar answered Oct 19 '22 01:10

Robert Jackson