Communication in ember

I am trying to figure out how to share data between my controllers / routes.

I have an application displaying company data. Here are the routes I want:

/ summary info /companies list of all companies with some more detail /companies/:id details about a single company 

Now the data needed for all three routes is contained in one company data array. Therefore, I want this data to be loaded when the application is launched, and then used for each route. There are also additional methods that I will need on the controller, which should be shared.

It is clear that the second and third routes are nested, so I can share data from CompaniesController when I refer to a specific company, passing data to this company:

 {{#linkTo 'company' company}}{{ company.name }}{{/linkTo}} 

But the consolidated route is where I get stuck. Two options that I came up with:

  • Create CompaniesController with any additional methods I need and create IndexController by expanding it

     App.IndexController = App.CompaniesController.extend({}); 

    Then, as far as I can tell, both routes will have to find models:

     App.Router.map(function() { this.resource('companies'); }); App.CompaniesRoute = Ember.Route.extend({ model: function() { return App.Company.find(); } }); App.IndexRoute = Ember.Route.extend({ model: function() { return App.Company.find(); } }); 

    It seems like there should be a better way, as I will have to repeat this for every new route I add (e.g. /revenue ).

  • Configure the summary route in the companies resource and specify the path '/'. What I don't like about this is that the "nesting" of my user interface does not match the data. It also seems that I will have to override the model property for each route.

Is there another option that is better?

tl; dr: How do I share data between controllers?

+6
source share
1 answer

To communicate with controllers, the right way would be to use the needs API .

Assuming your CompaniesController has all the data you want to make available to other controllers, you should define it with needs , it could be a simple string or an array of strings if you defined more than one.

 App.MyController = Ember.ObjectController.extend({ needs: ['companies'], myFunction: function() { // now you can access your companies controller like this this.get('controllers.companies'); } }); 

To make things more accessible, you can optionally define a binding, for example:

 App.MyController = Ember.ObjectController.extend({ needs: ['companies'], companiesBinding: 'controllers.companies', myFunction: function() { // now you can access your companies controller like this this.get('companies'); } }); 

Hope this helps.

+3
source

Source: https://habr.com/ru/post/949826/


All Articles