Blog

Ember.js - A Primer

June 01, 2016 by Damien White

Matches

All my previous Ember.js posts either walked you through examples or pointed out this or that about the framework. Well, if you read my last post, you may just be starting out with Ember and all those other posts may be over your head. Ember isn’t that complex, nor is it magic. In this post we’ll go over key constructs of Ember

Breaking Down Ember Into It’s Parts

Ember is composed of various parts. Creating a new Ember application using Ember-CLI and opening the app directory will give you a good idea of the most important parts of an Ember application (Figure 01).

Figure 01 - App Structure
Figure 01 - Ember-CLI App Structure

The Router

Let’s start from the most important part of Ember, and the entry to every one of your “pages”, the router. The router is the heart and soul of Ember. It’s what converts URLs into things that your users see. The router and routes are two separate parts, but work hand-in-hand. The router is where you say “hey Ember, I want my app to respond to books”. This is a single line in router.js, under the Router.map:

Router.map(function() {
  this.route('books');
});

Depending on your locationType setting (defined in config/environment.js; default is set to auto), this will give you a URL like /books (history/auto setting) or /#/books (hash/auto setting). The best bet here is to stick with auto, it will default to history for browsers that have the capability. If your users are using an old browser (I’m looking at you Internet Explorer), it will revert to using the hash setting for the URL and you don’t have to fuss with anything.

The Route

At this point we have a place to point our browsers at, but no content or way to load any data. Well, Ember-CLI can help us with this (or you can create the files manually, there’s no magic in Ember-CLI’s blueprint generators). The command to generate a route is simply ember g route <name>. In our case, we’re working with books, so we’d want ember g route books (where the g stands for generate, but who wants to type that all the time!). In the output, you’ll see what Ember-CLI has created for us (Figure 02).

Figure 02 - Ember-CLI’s generate route command results
Figure 02 - Ember-CLI’s generate route command results

It created three files for us, app/routes/books.js, app/templates/books.hbs, and tests/unit/routes/books-test.js. It also added the route books for us in router.js, which we did earlier. Don’t worry, it smart enough to know it already exists, so you don’t have two entries now. Like I said earlier, there’s no magic here and you could create these files yourself, but Ember-CLI makes it so much easier. Plus, Ember-CLI generates an appropriate test for whatever we are generating. This is a good thing because testing is ultra important. We’ll talk about testing a little later, but if you’re interested in TDD with Ember, I recommend you check out my tutorials published by my friends at Semaphore CI.

Let’s focus on the app/routes/books.js, since that’s the actual route object. The route is responsible for loading data for the template (the other file created app/templates/books.hbs). This might be confusing to you if you come from a server-side MVC framework and are thinking of those routes. Disconnect from that train of thought, we’re doing client-side development and models/data is loaded by the route. A route contains various hooks, but the one most commonly used is model. For example, continuing with the books example, we’d probably have something like this:

export default Ember.Route.extend({
  model: function() {
    return this.store.findAll('book');
  }
});

Here we are hooking into the model hook to return data for our template. In this case, we’re using ember-data (which gives us this.store.findAll) to load all the books from our API. We can now utilize this data in our template by referencing model (which is an array of books).

Templates

The next piece of the Ember.js framework is templates. These are hbs files, which is stands for Handlebars templates. Handlebars allows us to build “semantic templates”. Let’s look at a simple example of looping through our books model from the last section (within app/templates/books.hbs):

<ul>
  {{#each model as |book|}}
    <li>{{book.title}}</li>	
  {{/each}}
</ul>

You’ll notice that Handlebars is injected into standard HTML. It takes two forms, the block form like #each, note it starts with a # and ends like an HTML tag with /each. The other form is the inline version, which will output whatever is inside the Handlebars, in our example book.title will result in, you guessed it, the book title. Pretty straightforward, right? What if you wanted to add, for instance, a click event to each book (sort of a silly example, but let’s go with it)? In previous versions of Ember, before v2.0, you might have used a View to accomplish this task. Views have been deprecated and are gone in Ember 2.0+, but just know that these used to be used to inject JavaScript code into a template. Since Views are gone, let’s look at the replacement.

Components

Components are reusable bits of code. They are simply a Handlebars template and a JavaScript file. Components are not only reusable, but they can clean up your main templates dramatically. Not only that, in future versions of Ember, they will be introducing routable-components, so you can route directly to your component from the URL. Given that, it makes sense to prefer components for most functionality. Let’s take our book list for example, with Ember-CLI we can simply generate a component. Note that all components must contain a dash, this is to ensure that our components don’t bump up against future components provided by browsers. The command, as you probably guessed, is just ember g component book-list. It again creates three files for us, the JavaScript: app/components/book-list.js, the template: app/templates/components/book-list.hbs, and an integration test: tests/integration/components/book-list-test.js. Let’s move the template code out of the app/templates/books.hbs file and put it in the app/templates/components/book-list.hbs file instead. Now, let’s change the code a little because right now, our component doesn’t know what model is. Instead, we’ll create a property on the component (in /app/components/book-list.js) called books. We’ll give it a default of an empty array for now:

export default Ember.Component.extend({
  books: []
});

Ok, with that in place, let’s change our Handlebars template to use this new property:

<ul>
  {{#each books as |book|}}
    <li>{{book.title}}</li>	
  {{/each}}
</ul>

See what happened there? A subtle change, but it makes the code cleaner and more readable. Now, hop back into the template from the last section (app/templates/books.hbs), and we’ll use our component:

{{book-list books=model}}

That’s all there is to it. We are simply passing the model that came from the route into the component’s property: books. This has made our main template much cleaner, and if we wanted to we could use this component on as many templates as we choose, even inside other component’s templates!

Now, let’s look at how we’d add some interaction to our component like we talked about earlier, and one of our motivations for creating a component. Let’s say we want to add an action to each of the books when we click on them, we’ll just log to console for now as an example. We’ll first start by adding an action to our LI tag (which will correspond to us clicking on the item). We’ll simply add an action using Handlebars to the ‘LI’ and we’ll also pass a parameter to the action of the actual book so we can retrieve the title:

<ul>
  {{#each books as |book|}}
    <li {{action "bookClicked" book}}>{{book.title}}</li>
  {{/each}}
</ul>

If you run the app now and try clicking on a title, you’ll get an error in your console telling you no action bookClicked could be found. We can solve this by adding an action hash to the component’s JavaScript file:

export default Ember.Component.extend({
  books: [],
  actions: {
    bookClicked(book) {
      console.log(book.get('title'));
    }
  }
});

That’s all there is to it! Of course, this is a contrived example, but hopefully you get the idea of how a component works. While not everything fits nicely into routes, templates, or components, Ember has place for those things as well.

Services

From the docs: “An Ember.Service is a long-lived Ember object that can be made available to different parts of your application”. They go on to talk about examples such as Logging, User/Session authentication, and Third-Party APIs. Services can be injected into various parts of your application including routes or components. We actually looked at a service earlier when we talked about the route. The this.store that we have inside the route uses the Ember-Data service. Say in our sample application that we wanted to communicate with a third-party to get information about new books. This would be a perfect place to use a service. Like the other things we talked about, Ember-CLI can generate services as well. Generating one is easy, ember g service <service-name>. We won’t generate one here, but I encourage you to look up the example in the guides.

Models

We sort of glossed over models in the routes section, but they are an important part of an application. Again, I’m going to assume you’re using Ember-Data, and you have models that look something like this:

import DS from 'ember-data';

export default DS.Model.extend({
  title: DS.attr('string')
});

Now Models may not look that exciting, but without them, what data would we have? By using Ember-Data we’re able to access various back-ends to load our data without touching our models. We could use the JSONApiAdapter (which is the default for Ember-Data 2.0+), the RESTAdapter or even your own custom adapter. One setting to your configuration and Ember-Data will know how to communicate with your API through calls like findAll, findRecord`, etc. Think of it like an O/RM for APIs. Under the hood, it’s using standard jQuery ajax calls, so you could customize the settings globally if needed, extending one of the adapters.

Adapters and Serializers

We just talked about Adapters in the last section, but another piece of the Ember puzzle is a Serializer. Within a serializer, you can customize how your API responses and requests are handled. This is pretty advanced, but shows the power of Ember-Data. Just because there are a handful of common Adapters and Serializers doesn’t mean they may exactly fit your back-end API. You can customize just about every aspect of communication by extending or creating your own Adapters and Serializers. What’s an example of a serializer? Let’s say you are using the RESTAdapter and RESTSerializer. Instead of loading child objects asynchronously, you could extend the RESTSerializer to tell it that you want to use the embedded JSON included in the initial call to the API.

Helpers

These sort of fall under Templates, but we’ll discuss them here. There are times in your templates where you’ll want to format a number as currency or maybe format a date using moment.js. That’s where helpers step in. Helpers are simply functions that format a value given one or more parameters (typically). There is extremely good documentation in the Ember guides on writing helpers. I encourage you to check them out.

Controllers

I’ve saved these for last for a reason. Coming soon to Ember (well, maybe not that soon as I just saw a tweet from Yehuda Katz saying they aren’t going anywhere until at least 3.0), they will be deprecating controllers. As of today, they are still supported and are required to do a handful of tasks. If you want to support query string params in your application, you need to use controllers. That’s really the only thing I would use them for today. In the past however, before services and components, these were the workhorses behind the template. We had Controllers (the JavaScript part of the equation), Templates (the “view” if you will) and the View (for Template interactions, think like wiring up jQuery components). Now, controllers are still around, but in efforts to make the framework more accessible to more developers, components and services are both ways around using Controllers (except for those very few tasks I mentioned earlier). I say directly because even if you don’t create one manually, one is created for each of your templates automatically. Why? Well, remember the model hook in the route? When you return a model from there, there is another hook that fires called setupController. In that hook, by default, it sets the model property on the controller, thus how we have a model in our template. I mentioned that “in efforts to make the framework more accessible to more developers” earlier, and then went off on a tangent. With Controllers (and Views and Models), developers thought of Ember as an MVC framework. While it is, it’s client-side MVC, which doesn’t follow the same paradigm as a server MVC. This confused many developers. Separating thinking about server MVC from client-side MVC is difficult. Personally, I didn’t fall into this trap, but many have, thus a change of thinking for the future. Yehuda’s recommendation (as of 2016-03-17) is to not rush to port all your existing controllers. If you’re starting with a greenfield application, know that it’s still ok to use controllers, but I would recommend seeing if what you are doing would fit into a different “box,” if you will.

Tests

Testing your client-side application is important because the language we’re using is JavaScript. You won’t find your problems until you run your application. Last thing you want is to find the problems during production, so test! Automated testing is your friend. Out of the box, Ember uses QUnit for testing, though you could replace that with something else like Mocha if you choose. Whatever you decide to use doesn’t matter as long as you have tests. It’s hard to get to 100% code coverage unless you’ve TDD’d every last thing, but any percentage is better than 0. QUnit is very easy to get started with, and again I encourage you to check out my tutorials on Test-Driving an Ember.js Application for a lot more details on testing. I’ve also published a series here on the Visoft, Inc. Blogs, with one post talking about just testing straight JavaScript, one about unit testing Ember, and one about Integration and Acceptance testing with Ember.

Conclusion

I hope that you’ve found this post useful. We covered a lot of different pieces of the Ember puzzle. I pointed out just about every last little thing (e.g. adapters and serializers) that you may encounter in an application. Know that you don’t need to use things unless you explicitly need them. There are conventions in the Ember framework that make working with it very easy, and a lot of the time the defaults for things will suffice.

Single Page Applications - The Perfect Path

January 05, 2016 by Damien White

Choosing a Path

There is definitely no shortages of frameworks and libraries for creating single-page applications (known as SPAs). What exactly is a SPA you ask? A SPA is similar to a desktop application experience. The server loads a single page (one HTML page, with JavaScript and CSS), and all the typical interactions that you expect on the web occur on the client. JavaScript handles application structure, templating, routing, models, components, et. al. There’s a good chance that the client communicates with the server, but this occurs through AJAX requests instead of requesting standard web pages like a typical web application. Remember, there is only one HTML page, and the AJAX requests we make to the server is for data, not HTML markup. This approach makes the application feel more native. Think about applications like Google’s Gmail. Your mail loads automatically without you refreshing the browser. It feels like a native, desktop application.

So Many Choices

I mentioned earlier that there are no shortages when it comes to SPA frameworks/libraries. Let’s list of few of them.. Backbone, Angular, React, Ember, Aurelia, Meteor, Polymer, Knockout, and Mercury. Phew! That’s a lot right there, and I know I missed some. How do you decide which to use? Depending on your project you may choose one over another, but honestly, I feel one framework stands out from the rest.

Read More »

Ember.js - Articles You Can't Miss

December 02, 2015 by Damien White

Man Reading the News

There’s been a lot of activity in the Ember.js world over the past few months in the shift to 2.0 and beyond. Because of this, there have been many excellent articles on the web relating to Ember. I’d like to point out just a few of them today.

Common Ember Development Mistakes

First up is an excellent article by Balint Erdi on Toptal.com. Balint walks us through 8 Most Common Developer Mistakes when using Ember.js. It’s a comprehensive article pointing out some common mistakes that developers make using Ember.js. Balint takes it one step further and also points out Ember’s mitigation plan for helping developers. It’s a really good read. If you aren’t familiar with Balint’s other work, he’s the author of Rock and Roll with Ember.js. I applaud him for keeping the book up to date with Ember 2.0 changes. It’s nice to see a book that is evolving with the Ember framework.

More Ember Testing Fun

If you have been reading along with my other Ember posts on testing (e.g. Unit Testing Ember.js or Integration and Acceptance Testing with Ember.js), you may be interested in an article that I wrote for my friends over at Semaphore CI. It’s an in-depth article about Test-Driving Ember.js Models. It’s part of a series with more tutorials to come. In the series, we’ll be creating an Ember version of the website DevBookcase. It’s a site where software developers can keep track of the books they own. The actual site is written using Rails exclusively and figured it’s time to move it to more of a modern UI. There’s something magical about being able to sort and filter with ease on the client instead of relying on typical posts to do everything. If you want to know more about DevBookcase (and its sister EageReader.com, check out my old post about them.

Rails 5 API for Ember

It turns out that my second tutorial over at Semaphore about building an API to use with our Ember application using Rails 5 just got published last week. In the tutorial, I walk you through building an API using Behavior Driven Development (BDD) using the popular RSpec. We’ll be using this API going forward for our Ember application that we are building. Look for my next post when we move back to working directly with Ember.

Observers and Computed Properties with Ember.js

September 25, 2015 by Damien White

Looking Through Binoculars

Two powerful tools in the Ember.js world are computed properties and observers. If you aren’t familiar with these, don’t worry as examples of both will be given.

Computed Properties

First, let’s look at a computed property:

fullName: (function() {
  return this.get('firstName') + ' ' + this.get('lastName');
}).property('firstName', 'lastName')

This example is a very simple property. It just takes a model’s firstName and lastName and combines them. This property will be updated any time the model’s firstName or lastName changes. This is signified by the collection specified in the property method (the last line of the sample code). We could then take this property and use it in a template.

Read More »

Setting Up VirtualBox for Running ruby_odata's SampleService

April 23, 2015 by Damien White

OData

I was asked how to setup the SampleService used for integration testing the ruby_odata library (with Cucumber). If you’re not familiar with ruby_odata, it is a RubyGem used to communicate with OData services through Ruby. I’m happy to say that it’s been used in some rather large projects. The ruby_odata project contains tests that run in isolation (unit tests and acceptance tests), but there are also full integration tests that work against a “SampleService.” This service needs to run on Windows, and a lot of developers, including myself, use Linux or OS X as their development machine. In order to fully test ruby_odata, we’ll set up a virtual machine using VirtualBox and run the SampleService from there.

Initial Steps

I’m not going to bore you with the installation details of Windows, as I’m sure you’ve installed it before. I’m going to be installing Windows 8.1 Pro on a VirtualBox machine with 4GB of RAM. You can of course use another version of Windows, like Windows 7, but I figured I’d go with the latest release for this example. Once you have Windows installed, be sure to install the VirtualBox Guest OS Additions. Once you install the additions, make sure you reboot the virtual machine.

Figure 01: VirtualBox Guest Additions
Figure 01: VirtualBox Guest Additions
Read More »

Integration and Acceptance Testing with Ember.js

April 22, 2015 by Damien White

Ember: Tested

If you’ve been following along with my last couple of posts, welcome back. If not, I’d recommend you check out JavaScript Testing 101. You should especially read Unit Testing Ember.js since we’ll be continuing to build off the app we started in that post. In that post, we created a new Ember-CLI application and started unit testing our models (of which we only have one, contact), our controllers (where we have one, ContactsController), and our route (again, we have one, contacts). I have posted the complete code on GitHub for your convenience.

Integration != Acceptance Testing

Some people use the terms integration and acceptance testing interchangeably, but they are wrong. While the tests may look similar, that does not make them the same. Integration tests are tests between systems, ensuring that everything works in harmony. On the other hand, acceptance tests, are written from the point of view of a user. For example, we might write an integration test to verify that we can pull a list of contacts from the API. While if it were an acceptance test, we would test whether or not a list of contacts appear on a page. In this case, often, they may result in testing the same things, but from a different point of view. I just wanted to clarify the differences in case you were not aware of them. We are going to focus acceptance tests in this post because we want to focus on user interactions, and our tests will test the application end-to-end.

Read More »

Unit Testing Ember.js

March 20, 2015 by Damien White

Unit Testing Ember

Introduction

In my last post, I introduced you to testing JavaScript code with QUnit. Today I’ll be walking you through another example, but this time we’ll be using Ember.js as our framework. We’ll be building a small contact management application from the ground up using TDD along the way. Let’s get started!

New Ember Application

We’ll start by creating a new Ember.js application. We’ll do this using Ember-CLI, the preferred way to start a new Ember application (per the Emberjs.com website, Figure 01)

Figure 01: Snippet of the Ember Homepage
Figure 01: Snippet of the Ember Homepage

To get started with Ember-CLI, you’ll need Node.js and NPM installed, it’s as simple as going to the Node website and clicking the big Install button on their homepage. Easy-peasy. Then it’s simply two commands:

npm install -g ember-cli
ember new contacts

Then change into the contacts directory. Open that folder in an editor of your choice.

Finally, run the command ember serve to have your app served up on port 4200. Navigate to http://127.0.0.1:4200, and you should see a simple “Welcome to Ember.js” message.

Read More »

JavaScript Testing 101

March 06, 2015 by Damien White

Thumbs up for testing

Introduction

If you’ve been working with a lot of JavaScript or another dynamic language, you probably have come to the conclusion that you should have automated tests for your code. If you haven’t come to the realization yet, I suspect you’d like to make your life easier. Wouldn’t it be nice to know that your latest round of changes didn’t break your application without you having to manually go through every page in your application looking for issues? In this post, we’ll get started writing tests for our JavaScript code. For testing we’ll use the QUnit library. Why QUnit? First, it’s the oldest of the JavaScript testing frameworks. Also, Ember.js relies on it and in future posts I’d like to go into testing Ember code. Having this QUnit primer will help you test any JavaScript code, not just Ember code. Let’s get started!

Read More »

Ember + Emblem JS = Happiness

December 31, 2014 by Damien White

I’ve talked about Ember in my past few posts, and figured I would continue. Today we’ll look at an alternative templating library to Handlebars, Emblem.js.

Alternate Templating Engines

If you work with Ember, you’re very familiar with Handlebars. Handlebars makes it easy for us to add expressions to HTML. Writing HTML is great and all, but it’s very verbose. There are alternate templating engines available for server-side frameworks like ASP.NET MVC, and Rails. Two of these templating engines are Ruby Slim and HAML, both of which allow you to write slimmed down versions of HTML. But of course all of the engines render straight HTML as that is what browsers understand. Writing slimmed down HTML is advantageous for a few reasons. It definitely saves typing and thus time. Both Ruby Slim and HAML are sensitive to whitespace, meaning that your markup needs to be properly indented as indentation is important to determining hierarchy. With HTML, you can write all sorts of messed up code and how fun is that to maintain? We as developers usually try to keep our code properly indented, but these alternative templating engines, force us to maintain that standard. Finally, these alternate templating engines just make your code look nicer as well as easier to maintain. Why should the server get all the templating love? Now if only there were just a client-side version of something like Ruby Slim ;)

Read More »

Using X-Editable with Ember JS

November 12, 2014 by Damien White

In a couple of apps I’ve worked on, we’ve used the jQuery plugin X-Editable for entering values instead of bulky textboxes. X-Editable works nicely with Bootstrap and pops-up an editor in order to fill in a value. If you aren’t familiar with X-Editable, I encourage you to check out their demos. Figure 1 shows a simple screenshot of what a typical pop-up looks like.

Figure 01: X-Editable Popup Form
Figure 01: X-Editable Popup Form

Figure 2 shows that X-Editable can also do inline forms if you choose instead of a popup.

Figure 02: X-Editable Inline Form
Figure 02: X-Editable Inline Form

X-Editable works great, but what if you want to use it with Ember? That’s where I ran into a problem. You see, X-Editable changes the value that you have for you. We don’t want that. We want it to flow through Ember so everything is properly bound. Let’s start with how we might accomplish this goal. Read More »