Where do I put code for this?


I’m a Rails developer learning Ember, and getting a little confused, but liking it a lot.

I’m building the admin of a simple app, where the admin can approve posts before they go live.

I managed to list the posts, and now I want to show a count on the tab title.

Here is what I made so far:


What is the Ember way to show the post count?



First of all I took the liberty of updating your JSBin to the latest Ember and Ember Data. What’s the point of working with Ember if you aren’t using bleeding edge code from a day ago? *laughs that turn into crying*

When you want to show something in your template that isn’t directly from your model you should start thinking about controllers. A controller is like a decorator for the models and content that you’re showing in your template. The template you’re concerned with here is tied to your ApplicationController. That controller was generated by convention, so I needed to make an explicit one.

Next you need to know about computed properties. You want to present a property to the view that changes based on the number of posts you have.

postCount: function() {
  return this.get('allPosts.length');

Then you need to know a little something about how Ember Data works. It keeps a cache of all your records in something called a RecordArray. You can get at that guy by using something like this.get('store').all('posts'). This returns an instance of an ArrayProxy that will keep updating as you add and remove records.

Finally we need to create a property to hold allPosts on your ApplicationController so that you can watch it.

allPosts: function() {
  return this.get('store').all('post');

Rather than setting up this allPosts property on your ApplicationController, some might opt to instead look at the PostsController for the list of all posts. For that you would setup a needs relationship to the PostsController and your postCount function would look more like this:

postCount: function() {
  return this.get('controllers.posts.length');

What you want to do will depend on how and when you want to load your data, but that could be a pretty big topic in itself. Hope that helped!

Here’s the JSBin.


Thanks! Worked fine!