Chapter 7. JSON and Client-Side Frameworks

In Chapter 6, we took a look at a client–server relationship between the web browser and a web API. In this chapter, we will zoom the lens to the client side of that relationship, and see how some client-side frameworks are supporting or leveraging JSON.

Let’s take a quick look at what a framework is, for those that are not familiar with the concept. In the physical world, “framework” can be used to describe an essential supporting structure, or an underlying structure. In computing, a framework is not an underlying structure. It is a structure that sits on a layer above software or a programming language to provide support to the developers.

A framework in computing is a supporting structure, but not in a way that can be related to the beams of a building. If the JavaScript language were a house, a JavaScript framework would not be the supporting structure of that building. In fact, you can build a very strong house without a JavaScript framework.

If we were in the business of building houses with JavaScript, a JavaScript framework would be like ordering a prefabricated house that already contains plumbing and wiring for electricity. With our prefabricated houses, we could focus on creating whatever type of kitchen sink we wanted and running water would just be a matter of connecting the sink to the plumbing. We could focus on installing nice cabinetry and beautiful granite countertops. In essence, our JavaScript framework would allow us to save time and focus on building features.

This time-saving and focus-inducing framework is known in computer science as an abstraction tool. For those not familiar with the concept of abstraction, it may elicit images of Picasso’s art with strange faces made from shapes. Abstraction is not complex art, but a technique for dealing with complex systems.

If you were tasked with building a spaceship and you had no experience in rocket science, where would you start? Most of us would say, “Clearly I’m not the best person for this job,” but what if you had no choice? You could stare right into the face of that complex task and feel like it is impossible. You could panic and lock yourself into a room. Or, you could use abstraction.

With abstraction, you focus on one piece of the whole puzzle at a time. We break the task of building a spaceship into all of its essential pieces, such as supporting human life on the ship or launching the ship into outer space. We focus on each part of the complex system until the system is whole.

An abstraction tool is any tool that facilitates abstraction. A JavaScript framework facilitates abstraction with prefabricated libraries that have already dealt with complexities in the system. Not that we can build a real spaceship out of a JavaScript framework, but if we could that framework might contain a ship that can already launch into space. This would allow the ship builders to focus on how they are going to support human life inside the ship.

There are many (>50) JavaScript frameworks available today. Oftentimes they are referred to as JavaScript libraries or tool kits. Each of them creates a layer between the complex systems and your task at hand. Many of them allow for easy manipulation of the HTML Document Object Model, and others are focused on building full-fledged client-side web applications.

Let’s take a look at some JavaScript frameworks and their relationship with JSON.

jQuery and JSON

jQuery is an abstraction tool that allows developers to focus on building features by catering to manipulation of the HTML Document Object Model (DOM). The is a convention for interacting with the HTML page. In this model, the underlying HTML is treated as an object and a set of nodes that can be enumerated, accessed, and manipulated.

Manipulation of the DOM in JavaScript is possible without the jQuery framework. However, there are some things developers routinely need to do with the DOM that take several lines of code. For example, a common thing to do with the DOM is hide an HTML element. Let’s say I have a button that I want hidden (Example 7-1).

Example 7-1. An HTML button that displays in a web browser with the text “My Button”
<button id="myButton">My Button</button>

As shown in Example 7-2, to achieve the goal of hiding the button in JavaScript, I must call the function getElementById(id) on the HTML document object, then set the style.display property to "none".

Example 7-2. This line of JavaScript will hide the HTML button with the id “myButton”; it will not display in the browser
document.getElementById("myButton").style.display = "none";

jQuery achieves the same goal with less than half the characters in code (Example 7-3).

Example 7-3. This line of jQuery will hide the HTML button with the id “myButton”; it will not display in the browser
$("#myButton").hide();

Having to type less than half the characters to achieve the same goal saves on production time. In addition to saving time, jQuery also deals with Internet browser compatibility issues. For example, in Chapter 5, I brought up JSON.parse() as a safer   alternative to eval() for parsing JSON. In older versions of Internet Explorer, Firefox, and Chrome, JSON.parse() is not supported. This means whatever feature you wrote using JSON.parse() will not work for a small percentage of your users who fail to update their browsers.

jQuery deals with many common version compatibility issues for you, including the mentioned JSON.parse() issue. jQuery has a function for parsing JSON: jQuery.parseJSON. In Example 7-4, JSON is parsed with the JavaScript JSON.parse(). In Example 7-5, JSON is parsed with the built-in jQuery function.

Example 7-4. Parsing JSON in JavaScript with JSON.parse()
var myAnimal = JSON.parse('{ "animal" : "cat" }'),
Example 7-5. Parsing JSON with jQuery using jQuery.parseJSON
var myAnimal = jQuery.parseJSON('{ "animal" : "cat" }'),

In the examples, you can see that the jQuery example doesn’t appear to be saving any characters for typing. However, the jQuery.parseJSON() function is doing much more than one line of code. If you look at the function code for this in the jQuery library source, it attempts to use the native JSON.parse() function. If that is not available in the browser (for old versions), it falls back to using new Function(), which is the equivalent of using eval(). Additionally, there is some logic checking for invalid characters, which would be present in a script in an injection attack attempt, in which case an error is thrown.

In addition to jQuery.parseJSON, there is a function for making an HTTP request for JSON. If we take a look at our example from Chapter 6, we can see that requesting a resource over HTTP with JavaScript can require a good chunk of code (Example 7-6).

Example 7-6. This example code creates a new XMLHttpRequest object and gets JSON from the OpenWeatherMap API
var myXMLHttpRequest = new XMLHttpRequest();
var url = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139";

myXMLHttpRequest.onreadystatechange = function() {
    if (myXMLHttpRequest.readyState === 4 && myXMLHttpRequest.status === 200) {
        var myObject = JSON.parse(myXMLHttpRequest.responseText);
        var myJSON = JSON.stringify(myObject);
    }
}
myXMLHttpRequest.open("GET", url, true);
myXMLHttpRequest.send();

In jQuery, we can request the JSON resource by writing just a few lines of code (Example 7-7).

Example 7-7. This jQuery code will create a new XMLHttpRequest and retrieve the same JSON resource as the preceding example; this includes deserializing the JSON into a JavaScript object
var url = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139";
$.getJSON(url, function(data) {
   // do something with weather data
});

The jQuery JavaScript framework supports JSON in a way that cuts down on production time for requesting and parsing JSON. This includes parsing JSON in a way that support older versions of Internet browsers. We can say that jQuery supports interacting with  JSON. 

Now let’s take a look at AngularJS, a library that leverages JavaScript objects and JSON.

AngularJS

The jQuery framework is an abstraction tool that caters to manipulation of the Document Object Model (DOM). The AngularJS framework is an abstraction tool that caters to single-page applications. Single-page web applications are web pages that break away from the traditional multipage approach to create a more seamless application experience.

The traditional multipage web application experience is heavily tied to the human interaction between client and server. The human either types in or clicks a URL that makes a request for a resource with HTTP. This dance between the client and server and the human in a traditional web application involves each step “moving” to a new web page.

Before the Internet grew up into a beast that could handle the massive amounts of multimedia that it does today, most applications for the masses were desktop applications. If you wanted a digital encyclopedia, you installed it on your computer. The application that you interacted with was more or less seamless. When you searched for something in your encyclopedia, there was no URL bar with a page that changed addresses.

Single-page web applications seek to return to that seamless application experience right in your Internet browser. Quite a bit of this is achieved through JavaScript, and our good friend XMLHttpRequest. Instead of the human hopping from resource to resource through URLs and links to URLs, the code in the background handles the resource requests while the human remains on one page.

The AngularJS framework is an abstraction tool that saves the developer from having to build the single-page application from the ground up. The single-page web application is a complex system, and by no means does AngularJS build it for the developer. Instead, it provides a framework based on the model-view-controller (MVC) architectural concept.

AngularJS implements the MVC concept as follows:

Model
JavaScript objects are the data model.
View
HTML (uses syntax for data binding with the model).
Controller
The JavaScript files that use the AngularJS syntax defining and handling the interactions with the model and the view.

AngularJS can have a steep learning curve, especially for those that have been working with JavaScript and HTML Document Object Model (DOM) manipulations for years. It requires a shift in thinking about how to interact with the DOM. AngularJS seeks to decouple DOM manipulation from application logic.

This decoupling of DOM manipulation can be expressed by comparing how we would achieve the same goal without the AngularJS framework and with it. For example, I need to change a message on a page from the generic “Hello, stranger” (Example 7-8) to a personalized greeting when a user signs in (Example 7-9). In JavaScript, we would achieve this by manipulating the DOM.

Example 7-8. The HTML message when the user is not signed in
<h1 id="message">Hello, stranger!</h1>
Example 7-9. The JavaScript to change the message if the user is signed in
if (signedIn) {
    var message = "Hello, " + userName + "!";
    document.getElementById("message").innerHTML = message;
}

In AngularJS, as the HTML is our view, we set it up to prepare for changes in our data model (Example 7-10).

Example 7-10. The HTML view with AngularJS attributes and syntax for data binding
<body ng-app="myApp">
    <div id="wrapper" ng-controller="myAppController">
        <h1 id="message">Hello {{ userData.userName }}!</h1>
    </div>
</body>

The "ng-app" and "ng-controller" attributes on the HTML tags (<body> and <div>) are syntax for setting up the view to support data binding. Data binding is exactly what it sounds like: we are “binding” data to a page through a series of placeholders. The AngularJS syntax uses “handlebars” for these placeholders where data is to be bound. These handlebars are two open curly brackets ({{) and two closing curly brackets (}}) surrounding syntax for the placeholder (userData.userName in Example 7-10).

In Example 7-11, the JavaScript controller with a userData object is added to the global scope; this allows the view (the HTML) to use the object for data binding.

Example 7-11. userData object added to global scope
angular.module('myApp', [])
  .controller('myAppController', function($scope) {
    $scope.userData = { userName : "Stranger" };
    if(signedIn)
    {
        $scope.userData = { userName : "Bob" };
    }
  });

In the AngularJS JavaScript controller file, instead of manipulating the DOM, the data model is manipulated. The data model being manipulated is the userData object. Both the plain JavaScript/HTML example and the Angular example achieve the same functionality. For my simple example, the Angular way might seem like more effort, especially for an abstraction tool. However, when you delve into a complex application such as a page that allows users to perform create, read, update, and delete (CRUD) operations on their user info, the Angular way simplifies development.

Example 7-11 showed a JavaScript object userData for a data model. AngularJS leverages JavaScript objects by using them as the model in the MVC architecture. As we know, JSON is the notation for JavaScript object literals. So where does JSON fit in with AngularJS?

The question to ask is, “Where does our data model come from?” In the example code, my data model was hardcoded into the controller. If we return to the example of a digital encyclopedia, we know that data has to live somewhere. When data is stored, it is usually stored in a database of some sort.

How we get that data into the data model of our single-page web application is up to the developers. In an AngularJS data model, the most common vehicle for getting that data from the database to the data model is with JSON. This is often a JSON resource requested over HTTP, a client–server relationship. AngularJS leverages this relationship for retrieving data models easily with a core AngularJS service: $http.

In Example 7-12, the AngularJS $http is used to get weather data from the OpenWeatherMap API; the JSON is added to the global scope as an object named weatherData. The response appears in Example 7-13.

Example 7-12. Getting weather data from the OpenWeatherMap API
angular.module('myApp', [])
  .controller('myAppController', function($scope, $http) {
    $http.get('http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139').
      success(function(data, status, headers, config) {
            $scope.weatherData = data;
      });
  });
Example 7-13. The JSON response from the OpenWeatherMap API
{
    "coord": {
        "lon": 139,
        "lat": 35
    },
    "sys": {
        "message": 0.0099,
        "country": "JP",
        "sunrise": 1431805135,
        "sunset": 1431855710
    },
    "weather": [
        {
            "id": 800,
            "main": "Clear",
            "description": "sky is clear",
            "icon": "02n"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 291.116,
        "temp_min": 291.116,
        "temp_max": 291.116,
        "pressure": 1020.61,
        "sea_level": 1028.58,
        "grnd_level": 1020.61,
        "humidity": 95
    },
    "wind": {
        "speed": 1.51,
        "deg": 339.501
    },
    "clouds": {
        "all": 8
    },
    "dt": 1431874405,
    "id": 1851632,
    "name": "Shuzenji",
    "cod": 200
}

The JSON from the OpenWeatherMap API is deserialized by the AngularJS $http. After it is added to the global scope as an object named weatherData, it becomes our data model that we can bind to in our HTML view with handlebars syntax.

In Example 7-14, inside the handlebars syntax, the data being bound is the weather description. The weather description is in the weather property, which contains an array of objects, with only one value. I select the value at index 0 with weather[0] and then the property description.

Example 7-14. Binding the weather description
<body ng-app="myApp">
    <div id="wrapper" ng-controller="myAppController">
        <div>
           {{ weatherData.weather[0].description }}
        </div>
    </div>
</body>

At the time of writing this chapter, the weather was “sky is clear.” I could make this single-page application update every 60 seconds to deliver the description of the current weather. The HTTP request would happen behind the scenes, and the data model updating would automatically change the HTML view. The human would not have to initiate this request; this can all take place in the background. Additionally, with the MVC concept, the JavaScript code I write does not have to make the change to the DOM. Updating the data model automatically updates the view.

AngularJS leverages JavaScript Objects and JSON in its model-view-controller architecture. jQuery supports JSON with easy functions for requesting and parsing JSON. Much of the success of a data interchange format hinges on support by those who interchange data. In the client–server relationship of the Web, we can see that JSON is supported both by JavaScript and its powerful abstraction tools. In Chapters 8 and 9, we will see how JSON is supported and used on the server side of that relationship.

Key Terms and Concepts

This chapter covered the following key terms:

Abstraction
A technique for dealing with complex systems that involves focusing on smaller areas of that system.
Framework
An abstraction tool that saves time and allows for focus on building features.
jQuery.parseJSON()
A function that not only uses the JSON.parse() function, but uses a fallback for older browsers that doesn’t support JSON.parse() and handles the security hole of evaluating a string by validating characters.
jQuery.getJSON()
Shorthand for the jquery.ajax() function and parsing the JSON into a JavaScript object all in one.
Single-page web applications
Web pages that break away from the traditional multipage approach to create a more seamless application experience.
Model-view-controller (MVC)
An architectural pattern that divides an application into three components: the model (data), the view (presentation), and the controller (updates the model and view).
AngularJS
An MVC JavaScript framework that uses JavaScript objects as the data model.

We also discussed these key concepts:

  • jQuery is an abstraction tool that supports JSON by cutting down on production time for requesting and parsing data. Additionally, it handles browser-version support issues.
  • With the AngularJS MVC concept:
    • JSON is the model (or data model).
    • HTML is the view and uses syntax for data binding with the model.
    • Controllers are the Angular JavaScript files and syntax for defining and handling the interactions with the model and the view.
  • AngularJS leverages JavaScript objects and JSON in its MVC architecture.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.239.166