Search code examples
ember.jsember-dataember-cli

How do I reload data and update a bound element after a user clicks a button?


Why is it that when I click 'Random', the information in the template isn't reset and the data isn't update?

I have data that I want to display after a REST endpoint is successfully reached. The REST data that's returned is a random database record, so I don't need to worry about randomizing my request or anything. I only need to reach the server via that URL. In this case, the URL is: localhost:8000/api/verses/0

My handlebars template looks like this:

app/templates/verses.hbs

<div id="panel">

  <h3>{{model.reference_number}}
  <h3>{{model.body}}</h3>
  <button {{action "getAnotherVerse"}}>Random</button>

 </div>
{{outlet}}

So, when the 'Random' button is clicked, the following should be invoked:

app/controllers/verses.js

import Ember from 'ember';
import DS from 'ember-data';

export default Ember.ObjectController.extend({
    actions: {
        getAnotherVerse: function() {
            this.get('model').reload();
            // This is where the text should be reset to the new data.
        }
    }
});

app/routers/verses.js

import Ember from 'ember';

export default Ember.Route.extend({
    model: function() {
        return this.store.find('verse', '0');
    }
});

Solution

  • When you fire getAnotherVerse you just take the current record(model) and simply reload it to fetch its latest data. I guess you want to call model method of your route once again, so model will be reset and you'll get brand new record from your server.

    Move getAnotherVerse to your VersesRoute where you specify model for VersesController and try following code:

    # app/routes/verses.js
    model: function() {
      return this.store.find('verse', '0');
    },
    actions: {
      getAnotherVerse: function() {
        this.refresh(); # beforeModel, model, afterModel, setupController will re-fire
      }
    }
    

    If this still doesn't work, please try this:

    # app/routes/verses.js
    model: function() {
      return this.store.fetch('verse', '0');
    },
    actions: {
      getAnotherVerse: function() {
        this.store.unloadAll('verse'); # I assume `verse` is your Model name
        this.refresh(); # beforeModel, model, afterModel, setupController will re-fire
      }
    }