jeudi 14 janvier 2016

Ember.js 2.2 - How to update Route model from a Component?

With Ember 2.2.0, I have a Route:

Dash.BacklogReportsRoute = Ember.Route.extend
  model: ->
    @store.queryRecord "report", newest: true

and a Component:

Dash.BacklogReportComponent = Ember.Component.extend
  report: null
  actions:
    generate: ->
      # Send the request.
      $.ajax
        type: "post",
        url: "/reports/generate/#{new Date().getFullYear()}",
        success: =>
          # Update the model.
          # TODO - how to reload the model in place? Or at least just refresh
          # the Route so we don't have to reload the entire app.
          window.location.reload()

which includes as part of the template:

<p>
  Report was generated {{report.timestamp}}.
</p>

where timestamp is a computed property on the Report model.


The Route's model is the most recent Report object, and via the POST the generate action causes the server to create a newer (thus more recent) Report. I want to update the timestamp of that [newer] Report.

My question is, in Ember 2, how can I cause the Route to refresh itself? I'm new to Ember so I'm not sure if it's possible to access the Route directly from within a Component (or if I can, if it's a good idea). I don't think just reloading the model would work, because after a successful POST a different model (i.e. a record with a different id) will be returned by @store.queryRecord "report", newest: true than when the page loaded. The existing model will be the same after the POST.

Alternatively, I'd be perfectly happy completely rerendering the Route (it's a very simple page) or transitioning to "this" page again, but I can't figure out how to do that.

For now I'm simply forcing an old-school page window.location.reload().


Looking at this another way, perhaps there's a more idiomatic way to approach this problem with Ember.

Should I be loading in all (or some) Reports with the Route, and forcing a refresh on that Collection after the POST? I see Enumerable has a .firstObject property - is that a computed property (in other words, if my Routes model is a Collection of Reports and I push on to the front of that Collection, would that change propagate through .firstObject references automatically?)




Aucun commentaire:

Enregistrer un commentaire