Brant
Brant

Reputation: 15324

How do I structure an Ember.js app so I can access application state from itemControllers?

I have a collection of models, each of which stores a bit of application-persistent state on the controller. I want to access this state elsewhere in the app, but I'm not sure exactly how.

Here's a JS Bin with a stripped-down version of the app which demonstrates what I'm trying to do: On the "Boxes" route, I want to display a count of the number of clicked widgets, but from BoxController I don't know how to get access to the WidgetControllers that have that property.

If I understand the guides correctly, I should be able to use needs to inject one controller into another, but this doesn't really apply when I'm using itemController to wrap each model in its own controller instance.

Upvotes: 0

Views: 48

Answers (2)

tikotzky
tikotzky

Reputation: 2592

I would break it up into 3 parts...


1) Add a computed property to the App.WidgetsController the contains the checked widgets. Something like

clickedWidgets: Ember.computed.filterBy('@this', 'hasBeenClicked', true)

2) Add needs: ['widgets'] to the App.BoxController


3) Change the clickedWidgets computed property of the App.BoxController to get the list of clickedWidgets from the App.WidgetsController and the filter that list by widgets which match the box.

clickedWidgets: function() {
  return this.get('controllers.widgets.clickedWidgets')
    .filterBy('box', this.get('model')).length;
}.property('controllers.widgets.clickedWidgets.[]')

You can see a working bin here: http://jsbin.com/yizafe/1/edit

Upvotes: 1

user3995789
user3995789

Reputation: 3460

This should work for you, yes needs:['widgets'] is way to go: http://jsbin.com/tunuj/1/edit?html,js,output

Upvotes: 0

Related Questions