dcsimg

Bind Data to Your Web Forms with EmberJS Models

By Rob Gravelle

WEBINAR:
On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


Recently I made a life change. After 20 years of doing the 9 to 5 routine, I left my lucrative job as an IT advisor for the Federal Government to spend more time pursuing my varied interests. I like to say that I'm retired, but I am still shopping around for interesting contract gigs. In the field of Web development, EmberJS is a framework that keeps coming up time and time again. Its ability to manage complexity in modern web applications, along with its integrated development toolkit that enables rapid iteration, have strongly ingratiated it with developers worldwide.

In the Working with Data Models and Routes in EmberJS article, I described how to add Routes to our Sakila Video store app to link the pages of our app together. Then, in How to Link Between EmberJS App Pages, we created a navigation bar component to display site links at the top of every page. Now, it's time to bind a model to the rentals page in order to display available videos.

What is a Model?

If you've ever heard of Model-View-Controller (MVC), The Model of EmberJS is exactly what you think it is. For those of you who are not familiar with MVC, it's a common application architecture that divides an app into three interconnected parts. The MVC design pattern decouples the three major components of an application by allowing for efficient code reuse and parallel development.

With respect to data, it is separated into internal representations of information (Models) as well as how information is presented to the user (Views). In EmberJS, the Ember Data library is responsible for retrieving models from your server as JSON, saving updates back to the server, and creating new models in the browser.

Ember Data is based on the adapter pattern, so that it can be configured to work with many different kinds of backends. There are adapters for different many types of servers that save you from writing networking code.

Setting the Model

In Ember, the data model is loaded by the page's route handler. It does so via a special function called model(). The model() function acts as a hook that is invoked by Ember at different times in the app life cycle. For instance, the model() function we're going to add to our rentals route handler will be called when the user navigates to the rentals page via the "http://localhost:4200" or "http://localhost:4200/rentals" URL.

Open the rentals.js file, located in the app/routes directory, in your favorite editor, locate the export default Route.extend({ }) line, and add the model() function within the curly braces ({}). Then, return an array of rental objects from the model() function:

 model() {
   return [{
            "film_id": "1",
            "title": "ACADEMY DINOSAUR",
            "description": "A Epic Drama of a Feminist And a 
             Mad Scientist who must Battle a Teacher in The Canadian Rockies",
            "release_year": "2006",
            "rental_rate": "0.99",
            "length": "86",
            "rating": "PG"
        },
        {
            "film_id": "47",
            "title": "BABY HALL",
            "description": "A Boring Character Study of a A Shark And a Girl 
             who must Outrace a Feminist in An Abandoned Mine Shaft",
            "release_year": "2006",
            "rental_rate": "4.99",
            "length": "153",
            "rating": "NC-17"
        },
        {
            "film_id": "998",
            "title": "ZHIVAGO CORE",
            "description": "A Fateful Yarn of a Composer And a Man 
             who must Face a Boy in The Canadian Rockies",
            "release_year": "2006",
            "rental_rate": "0.99",
            "length": "105",
            "rating": "NC-17"
        }
    ]
}

The above code is an abridged version of the model() function. You can download the full code from Codepen.io. It contains many more rental items.

Ember supports ECMAScript 2015 (ES2015 or ES6 for short) style code. Note that above, we are using the ES6 shorthand method definition syntax; in ES6, model() is the same as writing model: function().

Ember will save the model object returned above as an attribute called model, which will be made available to the rentals template we generated with our route in the Working with Data Models and Routes in EmberJS tutorial.

Accessing Model Attributes

In the rentals page template - sakila-video\app\templates\rentals.hbs - we can reference the model attribute to display our list of rentals. Here, we'll use a common Handlebars helper called {{each}}. This helper is utilized to iterate over each of the rental objects in our model.

Update the existing code to this:

<div class="jumbo"> 
<div class="right tomster"></div> 
<h2>Welcome!</h2> 
<p>We have videos for every member of your family.</p> 
<hr />

<! -- <p>Videos will appear here…</p> -- >
{{#each model as |rental|}}
  <article class="listing">
    <h3>{{rental.title}}</h3>
    <div class="detail description">
      <span>Description:</span> {{rental.description}}
    </div>
    <div class="detail release_year">
      <span>Release year:</span> {{rental.release_year}}
    </div>
    <div class="detail rate">
      <span>Rental rate:</span> {{rental.rental_rate}}
    </div>
    <div class="detail length">
      <span>Running length:</span> {{rental.length}}
    </div>
    <div class="detail rating">
      <span>Rating:</span> {{rental.rating}}
    </div>
  </article>
{{/each}}
</div> 

On each iteration, the current object gets stored in a variable called rental. From the rental variable in each step, we can access individual attributes using dot notation, i.e. rental.length.

Viewing the Rentals Page

Now it's time to launch a console, navigate to the sakila-video project directory, and launch the server:

I:\>cd "I:\My Documents\articles\htmlgoodies\EmberJS\sakila-video"

I:\My Documents\articles\htmlgoodies\EmberJS\sakila-video>ember s


Build successful (36538ms) - Serving on http://localhost:4200/

Slowest Nodes (totalTime => 5% )              | Total (avg) --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  --  -- + --  --  --  --  --  --  --  --  --  -- -
Babel (20)                                    | 19972ms (998 ms)
BroccoliMergeTrees (9)                        | 2730ms (303 ms)
EslintValidationFilter (2)                    | 2388ms (1194 ms)
Funnel (8)                                    | 1837ms (229 ms)

In your browser, navigate to http://localhost:4200/ to see the updated rentals page.

Going Forward

Now that we've got our videos appearing on the rentals page, we can shift our focus onto beautifying and formatting the list. We'll accomplish that using a combination of CSS as well as Helpers.



Rob Gravelle

Rob Gravelle resides in Ottawa, Canada. His design company has built web applications for numerous businesses and government agencies. Email him.

Rob's alter-ego, "Blackjacques", is an accomplished guitar player, who has released several CDs and cover songs. His band, Ivory Knight, was rated as one of Canada's top hard rock and metal groups by Brave Words magazine (issue #92).



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date