EmberJS-Router Refreshing your Model



Description

If data in the model gets updated then, the Ember.js will refresh it periodically to display the updated values. The controller can send an action to the route. Calling the route's refresh method will re-execute the model hook again.

Syntax

refresh()

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Refreshing your Model</title>
      <!-- CDN's -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
      <script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
      <script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
      <script src="https://builds.emberjs.com/release/ember.debug.js"></script>
      <script src="https://builds.emberjs.com/beta/ember-data.js"></script>
   </head>
   <body>
      <script type="text/x-handlebars">
         {{outlet}}
      </script>

      <script type="text/x-handlebars" data-template-name="index">
         <h2>Information</h2>
         <!-- loop over the JSON data -->
         {{#each pr in model}}
            <p><b>Created at</b>: {{pr.created_at}}</p>
            <p><b>Title</b>: {{pr.title}}</p>
         {{/each}}
         <a href="#" {{action "getLatest"}}><i>Refresh the model</i></a>
      </script>

      <script type="text/javascript">
         App = Ember.Application.create();

         App.IndexRoute = Ember.Route.extend({
            model: function() {
               var url = 'https://api.github.com/repos/emberjs/ember.js/pulls';
               //get the JSON values from the specified url
               return Ember.$.getJSON(url).then(function(data) {
                 //adds the data to/from an array. splice(0,2) is the number of items to be displayed: is 2
                 return data.splice(0, 3);
               });
            },
            actions: {
               invalidateModel: function() {
                  //display message in the console of your browser
                  Ember.Logger.log('Route is now refreshing...');
                 //refresh the model
                  this.refresh();
               }
            }
         });

         App.IndexController = Ember.Controller.extend({
            actions: {
               getLatest: function() {
                  //display message in the console of your browser
                  Ember.Logger.log('Controller requesting route to refresh...');
                  this.send('invalidateModel');
               }
            }
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works:

  • Save above code in routing_rfrsh_mod.htm file

  • Open this HTML file in a browser.

Advertisements