WebAssembly in Action

Author of the book "WebAssembly in Action"
Save 40% with the code: ggallantbl
The book's original source code can be downloaded from the Manning website and GitHub. The GitHub repository includes an updated-code branch that has been adjusted to work with the latest version of Emscripten (currently version 3.1.44).
Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Friday, September 17, 2010

JSON Overview

When you have two components that need to talk to each other (over the internet for example) you need some way to pass data back and forth.

Up until recently XML was the solution that was often chosen as the data transmission format. Often times, the communication involved a very verbose form of XML known as SOAP.

More recently a new format has arrived that has begun to replace XML as the data transmission format of choice, especially when dealing with web sites and web applications, called JSON.

JSON stands for JavaScript Object Notation and is a lightweight data-interchange format that is easy for humans to read and write and is easy for machines to generate and parse. (I paraphrased this paragraph some from: http://www.json.org/)

Most major programming languages have support for JSON in one way or another through libraries or, in some cases, built right in. RESTful services in .NET, for example, can return XML or JSON.

Initially I thought JSON was just for objects, as its name suggests, but it turns out that it can be used to represent two different structures:
  • an Object
  • or, an Array

Creating a JSON Object

A JSON Object is created by having an opening curly brace ({) followed by name/value pairs.

Each name/value pair is separated by a comma (,).

The name/value pair itself is separated by a colon (:).

The name is a string but the value can be a string, number, object, array, true, false, or null.
Being able to use an object for the value portion of a name/value pair opens possibilities such as nesting additional JSON objects within a JSON object or creating functions within the JSON object.

The JSON object is closed by using a closing curly brace (})


JSON objects are declared and initialized in one step and result in what’s known as a singleton object.
Being able to create a singleton object is not unique to JSON. You can cause a standard JavaScript class to be created as a singleton object but there is a bit more work involved to do so. The difference is that, with JSON, the object cannot be declared in one spot and then initialized later like a standard class can be.


The following is the simplest JSON object you can create:
var objObject = {};

The above example is simply shorthand for writing the following:
var objObject = new Object();

The following is an example of a JSON object created that has two properties FirstName and LastName with the values Sam and Smith respectively:
var objEmployee = {
"FirstName": "Sam",
"LastName": "Smith"
};

Using the new objEmployee object in JavaScript is simply a matter of using the dot operator to access the properties that were created as in the following example:
alert("The employee’s name is: " + objEmployee.FirstName + " " + objEmployee.LastName);


Creating a JSON Array

To create a JSON Array you use an opening square bracket ([) followed by comma separated values and closed by a closing square bracket (])

The simplest JSON Array that you can create is an empty array using the following syntax:
var arrArray = [];

The above example is simply shorthand for writing the following:
var arrArray = new Array();

The following is an example of creating an array containing three strings:
var arrArray = [
"One",
"Two",
"Three"
];


Creating a JSON Class

It totally depends on your needs if JSON is the right choice for you when it comes to creating classes.

Some people find JSON classes simpler and easier to read. I personally don’t see a big difference between the readability of a standard JavaScript class and a JSON class.

If you’re happy with all of your members and methods in a class being public, creating the class using JSON is a bit simpler especially since you don’t need to declare the class first and then initialize it later. This is because a JSON object/class is automatically initialized as soon as it’s declared resulting in what is known as a singleton object since you only get the one object per class declaration.

This automatic initialization when the JSON class has been declared has its uses like if you wanted to have a global namespace object that contains some helper methods and don’t want to require the developer of the page(s) to initialize the object first before using the methods (acts like global functions but contained in a more structured class).


A JSON class is constructed the same way a simple JSON object is created but instead of a simple variable or object, you use a function as the value portion of the name/value pair as in the following example:
var Employee = {
"FirstName": "Sam",
"LastName": "Smith",

// Our method to return the Employee's full name
"GetFullName": function () {
return (this.FirstName + " " + this.LastName);
}
};

alert(Employee.GetFullName());


Converting strings of JSON into JSON objects

When requesting JSON data from a server it usually gets returned as a string of text.

Whenever possible it is recommended that the parsing of a string into a JSON object be done using the native browser methods if the browser supports those methods.

Converting a string of JSON into a JSON object, using the native browser object, is as simple as the following:
var sJSON = "{ \"FirstName\": \"Sam\", \"LastName\": \"Smith\" }";

var objJSON = JSON.parse(sJSON);

alert("JSON object's data: " + objJSON.FirstName + " " + objJSON.LastName);


In Conclusion

JSON is an interesting technology that can simplify some tasks as well as help to reduce the amount of bandwidth used when transmitting data between components over the internet/intranet especially when compared to SOAP.

The large number of libraries and built-in functionality for JSON also makes passing data using this format much easier.

Friday, August 20, 2010

Creating JavaScript Namespaces

As with any programming language there are many ways to accomplish a task and JavaScript is no different. What I'm about to show you is one way to create namespaces in JavaScript but other approaches exist too.

Organizing functions and variables into classes helps cut down on spaghetti code and introduce some organization to the JavaScript. Namespaces allow you to take that organization a step further and prevent class naming conflicts with other JavaScript libraries.

You can use JSON to create your namespaces but I tend to avoid JSON when creating classes because it does not allow for private members or methods.

The following is an example of how you would create a global namespace object (RootNamespace), add an object to the root object (ServerSideCalls), and then add an even more specific object to the newly added object (Products):

// Our root namespace so that our code does
// not interfere with other libraries.

// Also, being a global object already
// initialized allows calling code to access
// it
without needing to create an instance
// of a class first.
var RootNamespace = new function(){};



// Create a ServerSideCalls object within our
// RootNamespace object

RootNamespace.ServerSideCalls = new function()
{
// Private function
var GetXmlHttpRequestObject = function()
{

if(window.XMLHttpRequest)
{ return new XMLHttpRequest(); }
else if(window.ActiveXObject)
{ return new ActiveXObject("Microsoft.XMLHTTP");
}

}


// Public function
this.SendHttpRequest = function(sURL, sHTTPMethod, sData)
{

// Call the private function to get our
// XmlHttpRequest object

var xhrXmlHttpRequest = GetXmlHttpRequestObject();

// Send the request and return the response
// to the calling function

xhrXmlHttpRequest.open(sHTTPMethod, sURL, false);
xhrXmlHttpRequest.send(sData);
return xhrXmlHttpRequest.responseText;

}
};


// Go a step further and create a Products
// object within our ServerSideCalls object

RootNamespace.ServerSideCalls.Products = new function()
{
this.GetProductList = function()
{

// Call out to our web site to get the
// list of products

var sResult = RootNamespace.ServerSideCalls.SendHttpRequest("ourwebsite.com/products", "GET", "");

// Parse the return data into an array
var arrResults = [];
//...parse code

// Return the array of products
return arrResults;

}
};


Since we initialized our root namespace object when we created it, any code that needs to make use of the contained functions can do so without needing to worry about creating an instance of an object first as in the following example:

function TestNamespace()
{
// Ask for the array of products from our
// web site

var arrProducts = RootNamespace.ServerSideCalls.Products.GetProductList();

// do something with the returned array
// of products

}


You can always create the child namespaces objects within the parent namespace when you create that object. I don’t tend to take that approach because I usually separate my functionality into separate JavaScript files and add the object to the namespace only for the pages that need it.

In this example, I declared the root namespace object as a global variable. I have seen cases where the objects were simply added to the window object and the window object acted like the root namespace. I'm not sure if there are any issues with that approach so I error on the side of caution just in case adding items to the window object is not permitted by a browser in the future.