Search code examples
ember.jscontrollerember-datamodels

EmberData manage model in controller without route


I'm having a part of my applications split away from the main template in a sepparate handlebars template using {{render "header"}} to render that at the right place. This sepparate template also has its own controller to display some data from the model (App.Notification). What I want to do is display a limited amount of notifications and the number of new notifications in total. Ember data loads 10 entries from the server when the controller's notifications property is called in an each loop but as soon as I try to limit the amount of shown notifications via splice, it won't return any data.

Basically, I'm having trouble handling model data if I can't set the controllers model in a route, I assume that's why the normal syntax with slice isn't working in this case. I already searched Stackoverflow and the Ember docs but only found examples with normal Route -> Controller setup but nothing on this particular topic, so the question is, how to correctly handle model data in this setup?

Header Controller:

App.HeaderController = Ember.Controller.extend
  notificationNew: (->
    @get('notifications').filterBy('seen', false).get('length')
  ).property('notifications')

  notifications: (->
    @store.find('notification').slice(0, 2)
  ).property('@each.notification')

Template:

{{#each notifications}}
 ...
{{/each}}

Solution

  • To set properties on a controller not affiliated directly with a route by naming convention refer to the following jsbin.

    http://emberjs.jsbin.com/gugajaki/3/edit

    App = Ember.Application.create();
    
    notifications = [
      {seen: false, message: "tornado siren!!"}
      {seen: true, message: "Omg lol security breach"}
      {seen: false, message: "BFF Rite?"}
      {seen: false, message: "steve kane 4 prez?"}
    ]
    
    App.HeaderController = Ember.Controller.extend
      newNotifications: Ember.computed.filterBy("notifications", "seen", false)
    
    
    App.ApplicationRoute = Ember.Route.extend
      setupController: (controller, model) ->
      headerController = this.controllerFor("header")
    
      #this can be a remote fetch via find.  will work the same
      headerController.set("notifications", notifications)
    

    There are several issues in your posted code will are addressed in the link but I will enumerate here for clarity:

    1. You can use the length property directly in the template
    2. Use the Ember.computed.filterBy to get very efficient array observations
    3. Configure your singleton instance of the header controller by using the application route's "controllerFor" method
    4. I don't understand the splice but I wouldn't do it anyway

    Hope this helps.