ReactJS – functional reactive and declarative UI programming to the rescue

ReactJS is a JavaScript open-source library for creating user interfaces. It’s maintained by Facebook, Instagram and the open-source community. It can be tempting to think that ReactJS is just another JavaScript library that operates with the DOM, along with Angular, Aurelia, Ember or Polymer, but in reality it addresses a wider spectrum of edge cases, not just web applications: native development (iOS and Android), TV interfaces (Netflix), non-browser environment (server-side rendering), canvas graphics with video-like smoothness and others. What this means is that instead of ReactJS talking only to the DOM API, it just as well can be communicating with the Graphics Layers or WebGL – good old computer graphics programming.

ReactJS rendering layers

So basically ReactJS  is just a generic component model working for a lot of programming models and is going beyond the borders of W3C WebComponents and web applications, towards native iOS or Android development or even rendering directly with WebGL for complex 3D scenarios. The beauty of it is that you only need JavaScript to achieve this.
“You can think of ReactJS as a small library orbiting around the DOM. However as ReactJS is integrating with more and more things, the picture kind of flips around” (credits to Sebastian Markbåge):

ReactJS Integration

We all know that working directly with the DOM is slow. Because performance is crucial, one of ReactJS’s foundation stones is the Virtual DOM which makes the server-side rendering possible and allows re-rendering the entire UI every time the data changes without being prohibitively expensive. This means that ReactJS apps can easily run at 60fps even on mobile devices. Behind the scenes, the Virtual DOM relies on an efficient diffing algorithm that compute the minimal set of DOM mutations before actually touching it. The diffing engine works kind of the same way as the one used by the source repositories to stores the different revisions of a source file. Remember: whenever applicable, an algorithm will always find the best solution, whereas a human is prone to making errors.

Another important aspect of ReactJS is how it keeps the model in sync with the UI. With the traditional imperative programming paradigm, the way that you would normally handle this would be to initially render the markup at time = 0 and then manually sync its representation every time a change occurs in the model (time = 1, time = 2 etc.). For example, if you are using only jQuery to do the updates, the code quickly becomes spaghetti. With ReactJS you declaratively describe the UI at any point in time, not just the initial render, and let the view do all the required mutations when needed. It’s that simple: whenever there’s a change in the state, the entire thing is re-rendered. This is called one-way reactive data flow and will see how well it fits with everything else, especially with Flux, in some other article.

Speaking about programming paradigms, functional programming becomes a first-class citizen with ReactJS  not only in theory but also in practice, which means that the components are represented as idempotent and composable functions. The tree-like data structure resulted in the diffing process between two subsequent function calls will be transparently translated into a list of DOM mutation operations which ultimately will be reflected into the DOM. This is a big leap toward transforming theoretical functional programming concepts into actual code.

Prototypal inheritance in JavaScript

Is JavaScript an Object-Oriented Programming language? Does JavaScript support inheritance? Believe it or not, these are some tough questions that stir up endless discussions.

As in W3Schools.org, “JavaScript is THE scripting language of the Web” On Wikipedia, JavaScript is characterized as “a prototype-based scripting language that is dynamic, weakly typed, general purpose programming language and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles”.

However, form my point of view, if JavaScript supports object-oriented programming style, doesn’t mean that is an object-oriented programming language, at least not in the way that Java/C#/PHP 5+ is! I think that “JavaScript is an object-based language” is more realistic and closer to truth. However, one of the main characteristics of an OOP language is inheritance, which by the way is supported in JavaScript through prototyping.

Let’s see on code how we can achieve inheritance in JavaScript. First of all, let’s consider a “class constructor” called Human which could act as a base class:

function Human() {};

Since Human is a Function object (everything in JS is an object, even the Function!), it can have properties like “prototype”. In this moment, the prototype property of Human has an automated property called “constructor” which points to itself (to Human function).
If you try to debug this line of code with the Developer Tools from Chrome, you will have the following results:

Property ===> Expected result
DEBUG: Human.prototype ===> Human {}
DEBUG: Human.hasOwnProperty(‘prototype’) ===> true
DEBUG: Human.prototype.constructor ===> Human ()
DEBUG: Human.hasOwnProperty(‘constructor’) ===> false
DEBUG: Human.prototype.hasOwnProperty(‘constructor’) ===> true
DEBUG: typeof Human ===> ‘function’
DEBUG: Human instanceof Function ===> true
DEBUG: Object.getPrototypeOf(Human.prototype) ===> Object {}
DEBUG: Object.getPrototypeOf(Human.prototype) === Object.prototype ===> true

When an object is constructed, that object gets an implicit reference to the value of the constructor’s prototype property, which is an object. “Implicit reference” means an internal thing, not some property of the object. The implicit reference is hidden away, but it can be extracted with Object.getPrototypeOf(). E.g. When we write function Human() {}, Human has a new object constructed called prototype which “gets an implicit reference to the value of the constructor’s prototype property (Object.prototype)”. The “constructor’s prototype property” is finally an object (the base of all the things in JavaScript).

Property ===> Expected result
DEBUG: Object.getPrototypeOf(Human.prototype).constructor === Object ===> true
DEBUG: Object.prototype ===> Object {}

Next, consider the following line of code:

Human.prototype = {
  name : 'John'
};

After this line of code, the prototype will become a simple object, and because of poor JavaScript design, the prototype’s constructor property will point to Object (). That’s because the constructor property is no longer part of the Human.prototype, but rather of Object.prototype (if the property isn’t found in the prototype object, it is looked for in the prototype object’s prototype).

Property ===> Expected result
DEBUG: Human.prototype ===> Object { name : ‘John’}
DEBUG: Human.prototype.constructor ===> Object ()
DEBUG: Human.prototype.hasOwnProperty(‘constructor’) ===> false

Human.prototype.color = 'white';
Human.prototype.getName = function() {
  return this.name;
};
Human.prototype.getColor = function() {
  return this.color;
};

After these lines of code, the prototype will become Object { name : ‘John’, color : ‘white’, getName : function() { return this.name }, getColor : function() { return this.color } }
And now for the “object instantiation”:

var h = new Human();

Also the poor design of JavaScript is further reflected when instantiating the object h. That is, the contructor is not taken from Human.prototype, because as previously mentioned, the prototype of Human is a simple object with no automated constructor property and that’s why the constructor is taken from one level up which is from Object.prototype.

Property ===> Expected result
DEBUG: h.constructor ===> Object ()
DEBUG: Object.getPrototypeOf(h) ===> Object {
name : ‘John’,
color : ‘white’,
getName : function() {
return this.name;
},
getColor : function() {
return this.color;
} }
DEBUG: typeof Object.getPrototypeOf(h) ===> ‘object’
DEBUG: typeof h ===> ‘object’

To “patch” JavaScript’s poor design, we will create the constructor property which points to itself (to Human)

Human.prototype.constructor = Human;

Property ===> Expected result
DEBUG: Human.prototype ===> Human {
name : ‘John’,
color : ‘white’,
getName : function() {
return this.name;
}, getColor : function() {
return this.color;
}
}
DEBUG: Human.prototype.constructor ===> Human ()
DEBUG: Human.prototype.hasOwnProperty(‘constructor’) ===> true
DEBUG: h.constructor ===> Human ()
DEBUG: Object.getPrototypeOf(h) ===> Human {
name : ‘John’,
color : ‘white’,
getName : function() {
return this.name;
},
getColor : function() {
return this.color;
}
}

And now for the child class, which in our example will be called SuperHuman:

function SuperHuman(superpower) {
  this.superpower = superpower;
};
 
SuperHuman.prototype = new Human(); // inherit from Human
 
SuperHuman.prototype.getSuperpower = function() {
  return this.superpower;
};
 
var sh = new SuperHuman('laser');
 
SuperHuman.prototype.constructor = SuperHuman;

If you have the curiosity to debug the code and check the state of the properties after each line of code, you will see that SuperHuman will behave in the exact same way as Human did – that’s because SuperHuman inerits from Human and therewith all the design problems that we encountered before.

See ya!

HTML5 Websockets, Node.js And Socket.io On Windows

Assuming that you already Googled around for the terms “HTML5 WebSockets”, “node.js” and “socket.io” and you came to the point where you wanted to actually test it a bit, you can follow the steps below so that you can create the magic with your own hands.

“The server side”
What do you need to do in order to run your first WebSockets server on Windows:
– go to http://nodejs.org, download and install it
– in command prompt, go to C:\Program Files\nodejs and run the following command:

npm install socket.io

– under C:\Program Files\nodejs create a new file named server.js with the following content:

var http = require('http');
var io = require('socket.io');
 
//WebSocket
var server = http.createServer(function(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end('WebSocket server is up and running!');
}).listen(33334);
 
//Socket.IO
var socket = io.listen(server).set('log level', 1);
 
//Listeners for intercepting client messages
socket.on('connection', function(client) {
    client.on('message', function(data) {
        console.log('Message from client: ', data);
    });
    client.on('customMessage', function (data) {
        console.log('Custom message from client: ', data);
 
        var now = new Date().getTime();
 
        //Emits back to the client a message
        client.emit('customMessageResponse', data + '->' + now);
 
        //Broadcasts to all the clients a message
        client.broadcast.emit('customMessageResponse', data + '(broadcasted)->' + now);
    });
    client.on('disconnect', function(){
        console.log('Client disconnected');
    });
});

– in command prompt run the following command:

node server.js

– voila! the server is up and running
So far so good with the server side. But what about the client side?

“The client side”
– download a test HTML file from here http://goo.gl/9ul1O
– allow the file to be served by your favorite web server (IIS, Apache etc.)
Now for the tests!

“The magic”
– go to http://localhost/downloaded_html_file.html (for demonstration purposes, I will open it in 3 separate browser instances)
– almost instantly you should see the message “Client connected to the Server!”
– type something in the first input box, click on “Send Message!” and you should see the message in the WebSockets server log window, just like in the image below:

– now let’s test the broadcast functionality of the WebSocket – type something in the second input box, click on “Send CustomMessage!” and you should not only see the message in the WebSockets server log window but also in the 3 separate browser instances:

– if you’re curious to inspect the HTTP traffic (through Fiddler for example), you can see that in order to establish a WebSocket connection, the HTTP connection must be upgraded to a WebSocket connection (HTTP/1.1 101 Switching Protocols)

– unfortunately Fiddler logs the client-server communication in a way that’s a bit messy