Andy from Webcrunch

Subscribe for email updates:

How to REALLY Learn JavaScript Series: Part 9 JavaScript Frameworks
Portrait of Andy Leverenz
Andy Leverenz

July 1, 2015

Last updated November 5, 2023

How to REALLY Learn JavaScript Series: Part 9 JavaScript Frameworks

JavaScript was born out of the necessary need to manipulate elements on a web page and provide more interactivity than HTML and CSS alone were capable of. JavaScript will likely always remain as the go-to language for use in performing these enhancements. Almost every website makes use of JavaScript in some shape or forms these days so it’s essential for any good web developer to understand the language to the best of their ability.

Developers and designers alike, strive to find more than just interactivity within their websites and apps but rather faster response times, realtime updates, and more efficient code. There have been a plethora of new JavaScript frameworks that have popped up across the web lately. These frameworks work together with your front-end code (and sometimes author the front-end code) to make web pages or applications more dynamic and efficient than ever before.

In Part 9 of the How To REALLY Learn JavaScript Series I’ll introduce you to a few of the most popular frameworks to date as well as give you a quick introduction of each.

This is a long blog post. Towards the end of this article, I build a very simple Angular application. It is rather long and I wanted to preface this content with a quick warning/surprise to you. Hopefully, you don’t mind! If you want to jump to the Angular section feel free.

Download Source Code

Web Apps over Websites

Before you dive into a JavaScript framework you may need to ask yourself if your project even really requires one. There are a lot of websites out there built with so many frameworks which sadly end up being full of useless code (a.k.a. code bloat). Don’t fall into this trap with your own projects.

If your website is so simple that you only need static HTML and CSS, then you should only use those languages. There’s no need to install a CSS framework like Bootstrap or a JavaScript-like Angular.js for very minimal things you could author with your own custom code. That said, if you are in the beginning stages of your app or site and you want to quickly prototype your ideas then these frameworks turn out to be a Godsend because of how easy they are to install and use.

Web apps, compared to websites, are built to serve a purpose rather than be purely informational. Some websites provide both realms of this but for the sake of discussion, I’ll separate them in this way. New frameworks like [Angular.js]((https://angularjs.org/) and Ember.js entered the world to solve the problem of authoring dynamic HTML.

App-based websites require frameworks and a lot of JavaScript in order to work. Frameworks are made to help make your life easier.

In the end, remember to keep file sizes as small as possible, the number of frameworks to a minimum, and as concise of code as possible. People using your website or app will have very little patience when loading content or waiting for something to happen after performing an interaction.

Your app may fall into the JavaScript framework category and it may not. There are plenty of other languages out there to build your apps and some can be more powerful. Languages like Ruby, PHP, Python and more can be used to do similar functionality as JavaScript frameworks. The major draw to JavaScript-based frameworks is the lightweight file size and speed.

The Most Popular JavaScript Frameworks

Currently the most popular JavaScript frameworks are Ember, Backbone, and Angular. All of these frameworks have similar characteristics in terms of how data is rendered and bound to an HTML document. Each goes about this routing and manipulation in their own specific way but just remember you can use any of these three to perform the same functionality your application may require.

Ember.js

As stated on their home page, Ember.js is a framework for creating ambitious web applications. Out of the box, you can tie into their API to integrate very simple code into pre-existing HTML pages. It is a framework designed to build large web applications that compete hand to hand against similar native apps.

Ember makes use of Handlebars integrated templates that update depending on the state of data being sent or received.

These templates update depending on the HTML element(s) you write. Within separate JavaScript files you define the app as well as underlying objects which contain data that can be parsed from the front-end. This is what’s known as the MVC Model.

Installing

Installing Ember is relatively easy. You will need node.js installed and configured on your machine to install in the simplest way. Ember even has it’s own command line build tool called ember-cli which brings some built-in tools and add-ons to make your experience with ember that much more badass.

I could teach you step-by-step how to install ember but I think the website’s guide does a great job at this. Find out how to install it here.

General Ember Concepts

Ember makes use of templates which are written in the Handlebars templating language. Read more about Handlebars here.

Inside these templates are what ember calls Expressions, Outlets, and Components.

Expressions - consider these placeholders for dynamic content. Say you want a name to update your content based on what the user enters into a form somewhere within your app. Adding an expression to your template would be presented as {{Username}}.

Outlets - If you want to include a template inside another template to keep your code more concise and easier to manage. You can do that with outlets. These look similar to expressions {{outlet}}.

Components - A component is a custom HTML tag in which you create using JavaScript. You can configure how or where the component is displayed in the template. It can be configure as a unique HTML element <project-name></project-name> or as an attribute like this <div projectname></div>. This allows for the reuse of code and a very D.R.Y.(Don’t Repeat Yourself) approach to building your app.

Outside of the Handlebars templates and inside the JavaScript sector of Ember are the Router and Model

Router
Ember makes use of what they call a router. This translates a URL in a series of nested templates, each backed by a model(more on models in a second). As the models being shown change, Ember keeps the URL in the browser up to date in relation to what the user is seeing.

Models
In Ember, a model is an object that stores a state or data to later get converted. Templates are essentially the model being turned into HTML for the browser to render.

Putting it into practice

I pulled the example below from the home page of Ember’s site. It is a very basic example of how dynamic Ember makes a simple snippet of HTML.

The code below would go into the application.hbs file inside app/templates/application.hbs. Make sure you have the server running within ember to run this code in your browser once you save it. Try entering your name and watch it update dynamically.

<div>
 <label>Name:</label>
 {{input type=“text” value=name placeholder=“Enter your name”}}
</div>
<div class=“text”>
<h3>My name is {{name}} and I want to learn Ember!</h3>
</div>

You should see something like this.

Pulling Data From A Server

Similar to using jQuery, you can pull data from a server pretty easily with JSON and some custom functionality from Ember.

In your app.js file you’ll need to enter this block at the bottom:

App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    return Ember.$.getJSON(‘<your file path to JSON data>’).then(function(data) {
      return data;
    });
  }
});

Inside your template, you’ll need to loop through the data and display it by accessing parameters set within the JSON data returned. Ember’s example uses this type of code to render a list of pulls from their Github repo.

<h3>Last 3 Pull Requests to Ember.js</h3>
<ul>
{{#each model as |pr|}}
  <li>
    <div class=“issue-number”>#{{pr.number}}</div>
    <div class=“issue-title”>
      <a href={{pr.html_url}}>{{pr.title}}</a>
    </div>
    <div class=“author-name”>
      Opened by <a href={{pr.head.user.html_url}}><strong>@{{pr.head.user.login}}</strong></a>
    </div>
  </li>
{{/each}}
</ul>

Personal Thoughts on Ember

Ember is a pretty awesome framework in my opinion and is one of the innovators of this type of dynamic templating paradigms you see in other frameworks. Angular, for example, is incredibly similar but goes about a few things differently. One neat thing with Angular is that you only need to include a single JavaScript file instead of all of the other dependencies required for Ember. I’ll talk more about Angular in a bit.

Backbone.js

Backbone.js is a JavaScript library that adds structure to your client-side code. It essentially makes it easier to manage your application leaving you with code that is more maintainable.

Backbone is built upon the MVC structure. MVC stands for Model View Controller. This structure separates different parts of the application in a way that makes sense for the role each part plays. MVC Frameworks come in handy when you’re looking to maintain an advanced application with the least number of requests.

Developers should consider Backbone as it not opinionated; leaving you able to author your application in the way that best suits you. There is some out of the box structure you can make use of or you can always extend it.

Templates
Backbone doesn’t supply a specific templating engine thus giving you the freedom to use whichever you please. Common templating frameworks to use with Backbone are Underscore.js and Handlebars.js

Backbone Examples
I think with backbone.js it is easiest to understand by jumping straight into examples. Check out the structure below (source).

Say we want to build a simple to-do type of application. We can use Backbone and it’s MVC structure to go about this fairly easily.

<!— todo.html —>
<!doctype html>
<html lang=“en”>
<head>
  <meta charset=“utf-8”>
  <title></title>
  <meta name=“description” content=“”>
</head>
<body>
  <div id=“todo”>
  </div>
  <script type=“text/template” id=“item-template”>
    <div class=“view”>
      <input id=“todo_complete” type=“checkbox” <%= completed ? ‘checked=“checked”’ : ‘’ %> />
      <label><%= title %></label>
      <button class=“destroy”></button>
    </div>
    <input class=“edit” value=“<%= title %>”>
  </script>
  <script src=“jquery.js”></script>
  <script src=“underscore.js”></script>
  <script src=“backbone.js”></script>
  <script src=“todo.js”></script>
</body>
</html>

Here the example requires the <div> element with an id of todo. We also need a template containing placeholder information for a basic to-do item. You’ll see at the bottom of the file we included jQuery, underscore.js, backbone.js, and a todo.js file for our own code. Underscore.js’ is a good contender when it comes to templating with Backbone. A lot of developers use this combination as you might find out and hence why you see it here.

In our todo.js file we create Backbone models to hold data for each to-do item.

/* 
 todo.js
*/

// Define a Todo Model
var Todo = Backbone.Model.extend({
  // Default todo attribute values
  defaults: {
    title: ‘’,
    completed: false
  }
});

// Instantiate the Todo Model with a title, with the completed attribute
// defaulting to false
var myTodo = new Todo({
  title: ‘Check attributes property of the logged models in the console.’
});

We need a way to get our model to render into our initial HTML from earlier. To do this we create a Backbone view that defines the type of element, what kind of events, and any call back functions on those events. It looks a little complicated but the view is doing quite a few things to render our data on the page.

/*
  todo.js
*/

var TodoView = Backbone.View.extend({

  tagName:  ‘li’,

  // Cache the template function for a single item.
  todoTpl: _.template( $(‘#item-template’).html() ),

  events: {
    ‘dblclick label’: ‘edit’,
    ‘keypress .edit’: ‘updateOnEnter’,
    ‘blur .edit’:   ‘close’
  },

  // Called when the view is first created
  initialize: function() {
    this.$el = $(‘#todo’);
  },

  // Re-render the titles of the todo item.
  render: function() {
    this.$el.html( this.todoTpl( this.model.attributes ) );
    this.input = this.$(‘.edit’);
    return this;
  },

  edit: function() {
    // executed when todo label is double clicked
  },

  close: function() {
    // executed when todo loses focus
  },

  updateOnEnter: function( e ) {
    // executed on each keypress when in todo edit mode,
    // but we’ll wait for enter to get in action
  }
});

// create a view for a todo
var todoView = new TodoView({model: myTodo});

If you refer to the HTML earlier you may have noticed some new syntax styles within the view div. That syntax is what underscore.js uses to display dynamic data on the page. The templating engine connects with the model and controller to work to bring the data.

Personal Thoughts on Backbone
Truth be told. I find Backbone.js to be the most confusing of the three frameworks I’m discussing in this article. It is used by many wells know applications you probably use often such as Disqus, Flow, Airbnb and more.

I’ve only meant to touch briefly on each framework so apologies if this isn’t quite in-depth but as with any language or a new tool you need to learn by doing. I followed along with a few resources to get more familiar with Backbone on my own. Take a look for yourself if you’re interested in learning more.

Angular.js

The almighty Angular.js framework is currently taking the web app and mobile app world by storm. More and more apps are using Angular for its extensibility, ease of use, and powerful features.

Other frameworks deal with HTML’s shortcomings by either abstracting away from the HTML and CSS itself or by providing a poor way to manipulate the DOM. Angular tries to fix that by offering many solutions to common problems we face within static content like HTML.

Angular plays nice with other libraries. Every feature can be modified or replaced to suit your own developmental needs. It, like the other frameworks I’ve discussed., is an MVC type of framework developed by Google.

Installation

Installation is a breeze. For Angular, all you need to do is include a