Andrew
Andrew

Reputation: 1013

Update ember component on model change

Using Ember 1.13

I have two nested resources, one of which renders a component based off the model returned by a dynamic route

something like

Router.map(function() {
  this.resource('maps', function () {
    this.resource('map', { path: '/:map_id' });
  });
});

and a template for a map which renders a component

map.hbs

{{some-component model=model}}
{{#each maps as |map|}}
  {{#link to 'map' map}}{{map.name}}{{/link-to}}
{{/each}}

when I first hit

/maps/1

the component renders

when I hit one of the links and go to

/maps/2

it appears as if the route never gets hit and the component never updates

is this a result of using link-to or is it true the route is not getting hit because just changing the model inside of a route does cause the same lifecyle hooks to go off?

What is the best way to force this component to rerender?

Upvotes: 3

Views: 3066

Answers (1)

You're probably doing something wrong.

Here's a basic working example:

<h3>maps.index</h3>

<ul>
{{#each model as |item|}}
  <li>
    {{link-to item.name 'maps.map' item}}
  </li>
{{/each}}
</ul>
<h3>maps.map</h3>

{{link-to "Back to index" 'maps.index'}}

<hr>

{{x-map map=model}}
<h4>components/x-map</h4>

<p>Id:   {{map.id}}</p>
<p>name: {{map.name}}</p>
App.Router.map(function() {
  this.route('maps', function () {
    this.route('map', { path: '/:map_id' });
  });
});

App.MapsIndexRoute = Ember.Route.extend({
  model: function () {
    return this.store.findAll('map');
  }
});

App.MapsMapRoute = Ember.Route.extend({
  model: function (params) {
    return this.store.findRecord('map', params.mapId);
  }
});

App.Map = DS.Model.extend({
  name: DS.attr('string')
});

Demo: http://emberjs.jsbin.com/voquba/4/edit?html,js,output

Note that instead of passing the whole record into the child route:

{{link-to item.name 'maps.map' item}}

You can pass only its ID:

{{link-to item.name 'maps.map' item.id}}

This is useful when you know the ID but don't have the whole record at hand. Ember Data will look up the record of given ID in the store. If it's not there, it'll fetch it via the route's model hook.

Upvotes: 2

Related Questions