EmberJS-Models Customizing The Adapter



Description

If your JSON API is stored other than host root, prefix the URL to all requests by overriding the properties and methods of Ember.js to customize how records are retrieved and saved.

Syntax

DS.RESTAdapter.extend({
   //include the adapters
});

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Customizing The Adapter</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" data-template-name="fruits">
         <h1>Namespace is: <small>{{namespace}}</small></h1>
      </script>

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

         Fruits.ApplicationAdapter = DS.FixtureAdapter.extend();

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

         Fruits.FruitsAdapter = DS.RESTAdapter.extend({
            //set namespace property
            namespace: 'api',

            //default adapter
            defaultSerializer: '-default',

            //setting up the host property
            host: 'https://tutorialspoint.com',

            //Custom Http Headers
            headers: {
               'API_KEY': 'secret key',
               'ANOTHER_HEADER': 'Some header value'
            }
         });
      </script>
   </body>
</html>

Output

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

  • Save above code in model_cust_adp.htm file

  • Open this HTML file in a browser.

Advertisements