neverfox
neverfox

Reputation: 7010

Ember ArrayController content undefined after init

I have an ArrayController as follows:

DashboardController = Ember.ArrayController.extend
  content: []

  xFormatter: (x) ->
    d3.time.format("%m-%d") x

  init: ->
    console.log("dashboardController init")
    @_super()

    y = undefined
    currentDate = undefined
    i = 1

    while i < 30
      currentDate = new Date("12/" + i + "/2011")
      @content.pushObject
        x: currentDate
        y: (Math.random() * 100) / 10

      i++

When the app initializes, the controller is created (as indicated in the console) and content is pushed into the array during init, but content is undefined when I try to access it from elsewhere (e.g. a view). I tried content: null, then doing @set("content", []) at the start of init but got the same result.

The Ember guides say to set an ArrayController's content property in my route's setupController method to tell it what model to represent, but since this "model" is a really the result of a function, I'm not sure how to go about that. I thought that since init is run for each created instances, each instance would get a populated content without using setupController.

I think the example I pulled this from is using a old approach not suitable for 1.0.0-rc1. How should I restructure this to work?

Upvotes: 1

Views: 1337

Answers (2)

Ramiro Jr. Franco
Ramiro Jr. Franco

Reputation: 286

A simple fix ( as of EmberJS 1.0.0rc-3 ) is to define the model in the route to the controller content in cases where it already exists. Like So (pardon the coffee script):

App.MyRoute = Em.Route.extend
  model: ->
    @get('controller.content') || App.My.find(query)

There was a change in master though, that prevents this from working, so you might need to do

App.MyRoute = Em.Route.extend
  model: ->
    controller = @controllerFor('my')
    controller.get('content') || App.My.find(query)

Upvotes: 1

neverfox
neverfox

Reputation: 7010

Ok, so it seems that the trick is to move the code that generates the values to the model hook of the route, then use the setupController hook to set the controller's content. The only thing I don't like about this is that the data is generated every time there is a transition to the route (since the model and setupController hook are called each time). I'd like to have it calculated once and cached. I suppose the way to do this would be to create an Object that either creates new data the first time or returns the cached data, then call on this Object in the model hook.

Upvotes: 0

Related Questions