Question

I have a list of categories that I would like to display on the page. I've been looking around for hours on the correct way to do this, but I keep finding conflicting information and methods that are either no longer working with the current version of Ember, or are deprecated.

To create the app and Ember-Data thing:

var App = Ember.Application.create();
App.ApplicationAdapter = DS.FixtureAdapter;

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

I am using Ember-Data with some fixture data for the categories:

App.Category.FIXTURES = [{
  id:          1,
  name:        'Category 1',
  description: 'The first category'
}, {
  id:          2,
  name:        'Category 2',
  description: 'The second category'
}];

I then create a model to represent an instance of a category (the "versions" relates to a different model where version instances have category instances):

App.Category = DS.Model.extend({
  versions:    DS.hasMany('version'),
  name:        DS.attr('string'),
  description: DS.attr('string')
});

Then I made an ArrayController, but I am having trouble populating the content.

App.CatagoriesController = Ember.ArrayController.create({
  content: [],
  init: function () {
    this.set('content', ???);
  }
});

This isn't hooked up to a route since it isn't navigable, so I can't use the "model" property in a route.

Replacing the ??? in the ArrayController, I've tried several things:

I tried this.store.find('category') like the examples show for routes, but I get the error "Uncaught TypeError: Cannot read property 'find' of null".

I tried App.Store.find('category') and that gave me the error "Uncaught TypeError: undefined is not a function".

Any help or a push in the right direction is appreciated. I have a feeling I'm not even headed in the right direction.

Was it helpful?

Solution

A couple of things.

First, remember that controllers are singletons. So your init function will only fire once for the entire lifecycle of your application (which probably isn't what you want). But that doesn't really matter, since...

The way that you're handling models isn't the way that Ember.js is set up for. You shouldn't be fetching models in controllers, only routes. That's why there is no store property on the controller. You need to implement the model hook on your route, like this:

App.CategoriesRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('category');
    }
});

From there, Ember will automatically set the model property (not the content property, don't use that) on your controller to the data that you return from the model hook.

So, just eliminate the content property and init function from your controller, and implement that hook in your model, and you should be good to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top