12 Days of Posts: Day 9 – thinking in React

We are going to continue our journey into the functional paradigm. In many posts I have made it clear that I like React. Which leads us to the question, why?

In the simplest terms, React is functional. It is best utilized when functional ideas are used to design and build components. This forces most programmers to have to think differently. Think in React, as it were.

What makes React functional? Functional programming gets its name from Mathematics. The definition of a function in Mathematics is:

a function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output.

This means that we should build React components in such a way that they will only have one output for each input. This may seem simple, but becomes harder the more we think about it.

Image a few years ago and we are programming in jQuery (not that there’s anything wrong with that). We have a list of items and a few different ways that someone can add to the list of items. Someone adds a new item, what is the output of the list? It depends. It depends on what has happened before. Application state is held in the list. We cannot state with any certainty that an input will map to one output.

With React we will just build a component that renders a list. The component will not worry about where the data comes from or how someone can modify the list. If 3 items are passed in, that is what will be rendered. This is functional.

The core idea of React is to build composable components. This means that we start with very simple components which can then be put together to build larger and larger components until we have an entire application. Each one of these components should be functional in nature. They should not hold state and only render what is handed to them. This breaks down how large of a mental model is needed to work on each separate component.

There is a good question to be asked. If all components do not hold state, how do we have an actual application? Does state not have to be changed? If no state is changed, did we not just create a static HTML page? All good questions. We will look at them tomorrow.

Here is a presentation I gave at a local meetup where I cover thinking in React.

12 Days of Posts: Day 4 – using call and apply

We have seen some ways that we can take advantage of JavaScript’s functional roots. This theme will continue for this post as we will look at call and apply.

Call and apply are very similar. Both methods will execute the function, set the this value and pass in parameters. Call does this by having the parameters each explicitly defined while apply takes an array of parameters. Here is an example using our trusty add function and whatIsThis.

function add(x, y){
  return x + y;
}

function whatIsThis() {
  console.log(this);
}

console.log(add.call(undefined, 1, 2));
//returns 3
console.log(add.apply(undefined, [1, 2]));
//returns 3
console.log(whatIsThis.call({prop: 'test'}, null));
//returns Object {prop="test"}
console.log(whatIsThis.apply({prop: 'test'}, null));
//returns Object {prop="test"}

We can see the differences in execution, but the result will be exactly the same.

These examples are arbitrary so let’s build a little less arbitrary example. Let’s imagine that we have a comparing object that has a function to make a comparison. We want to make it so that the comparison function can be changed at a later point in time. We can use apply to make this easy. Here is that example.

var newCompare = function(a,b) {return a>b;}

var comparer = {
  compareFunc: function() {
    return false;
  },
  compare: function compare(a, b) {
    return this.compareFunc.apply(this, [a, b]);
  }
}

console.log(comparer.compare(5,1));
//returns false
comparer.compareFunc = newCompare;
console.log(comparer.compare(5,1));
//returns true

The compare function just executes another function. This means that we can change it out whenever we need to. The best part is that the new function does not need to know about the current object as it will all of its context passed to it by apply.

I have a real world example of this in my Webcam library. The library has a draw function, but we can change it out whenever we want. The new function will have access to a canvas, the 2d context, the 3d context, and the video stream. We can see the code on line 130 in video.js.

Here are all the examples in jsFiddle.

12 Days of Posts: Day 3 – using bind with a function

We are already at day 3. We are continuing with JavaScript and building on what we have already covered. We are going to cover the bind method of the function object.

Bind is used to define what this is inside of a function. It will return a new function (there is that ‘functions are a first class object’ idea again!) and not modify the current function. Let’s look at an example. Here is a simple function:

function whatIsThis(){
  console.log(this);
}
whatIsThis()
//this will return the window object

The default this value for an anonymous function will be the window object. We will now bind a new value for this using bind:

var newBoundWhatIsThis = whatIsThis.bind({property: 'Test'});
newBoundWhatIsThis();
//this will return Object {property: "Test"}

We have changed the value of this with bind. This will allow us to build functions that can operate on many different objects as long as the objects all have the same properties. Here is an example.

var josh = {name: 'Josh'};
var brian = {name: 'Brian'};
function outputName(){
  console.log(this.name);
}

outputName.bind(josh)();
outputName.bind(brian)();

Here outputName can operate on both objects.

Finally we will use bind to partially apply parameters. This is the same concept as the last post. Any other parameters passed into bind will be prepended to the list of arguments when executed later. Here are the examples from the last post, but this time with bind.

var boundAddOne = add.bind(window, 1);
boundAddOne(5);
//will return 6

var boundAddTen = add.bind(undefined, 10);
boundAddTen(5);
//will return 15

The add function does not do anything with this so it does not really matter what we use. We then pass in the first parameter so that a new function will be returned that will accept one parameter.

Here are all the examples on jsFiddle

12 Days of Posts: Day 2 – Partial application of a function

This day’s post is a continuation of the last post. In the last post we covered that a function can return a function, but we did not cover any use cases. This post will discuss a very useful one.

We have an add function:

function add(x, y){
  return x + y;
}

We can partially apply one of the parameters and return a new function. To reinforce what this means we will look at an example.

function partiallyApply(param, func){
  return function(nextParam){
    return func(nextParam, param);
  }
}

var addOne = partiallyApply(1, add);

The variable addOne takes the add function and partially applies one of the parameters (y is now always 1). When we execute partiallyApply we bind the first parameter and return a new function which allows us to bind the other parameter later. This means we can do this:

addOne(5);
//returns 6
addOne(10);
//returns 11
var addTen = partiallyApply(10, add);
addTen(5);
//returns 15

What good is this? Well we essentially are passing in parameters over two separate points in time. I had a problem where I needed an index for an item in a list and the event object. The issue was that I did not have these two things at the same time. The event object is only created in response to an event. I partially applied the index first which returned a function that would accept the event object. I have the code in the react_components.js file in my Where to eat repository.

The next post will continue the JavaScript theme.

12 Days of Posts: Day 1 – Functions can return functions

I am attempting to do something a little different. Right now everywhere you go there is something related to Christmas. This inspired me to challenge myself to write 12 short posts before Christmas. Here is the first.

Functions can return functions

In JavaScript functions are first class objects. For our purposes here that means that functions can be returned from other functions, used as parameters for other functions, and the value stored in a variable.

This means we can take a simple function like this:

function add(x, y){
  return x + y;
}

This is a completely arbitrary function but we will build another function to return this one.

function returnAFunction(){
  console.log('In returnAFunction');
  return add;
}

This just has a console call to let us know when we execute it and then it returns our add function.

Here are some things that we can do with this now:

var returnedAdd = returnAFunction();
//console logs In returnAFunction
returnedAdd(1,2)
//the output would be 3
returnAFunction()(2,2)
//console logs In returnAFunction
//the output would be 4

First we capture the returned function as returnedAdd. We can then use that as if it was our add function. Next we execute returnAFunction and then immediately execute the returned function. This demonstrates the first class nature of functions. Functions are not some special type that must be defined first and then executed. We can pass functions around just like we would any other object.

Why would we do this? The post tomorrow will build on this idea and answer why would we do this.

My talk on React

This is a talk I gave for a local Meetup about React. It is called ‘Why I like React’. I cover the basics of building React components. Then I spend some time talking about functional programming. Finally I wrap it all together to show how React is functional in nature. The final demo shows how to ‘think in React’.
Continue reading “My talk on React”

A talk on building packages for Node.js

This is a talk I gave for a local Meetup about node.js. I cover building an Express-like package from scratch. It does not have all the features of Express and is not ready for production. It does show you how to build a package including testing. The example package is at https://github.com/johanan/example-simple-app. The project in the video is at https://github.com/johanan/Local-Variables-Dec-2014.
Continue reading “A talk on building packages for Node.js”

Book Preview (Building Scalable Apps with Redis and Node.js)

Download the src(github). This is all of the code from the book.

I am excited to present an excerpt from my book, Building Scalable Apps with Redis and Node.js. It is from the second chapter entitled Extending Our Development with Socket.IO. In the first chapter we created a simple Express app and now we are rolling in Socket.IO. This is only the end of the chapter. I, of course, highly recommend the book and hopefully after reading this you will agree.

This has been adapted from the source to better fit my blog’s presentation and has a few typos fixed, which means that there are a few typos in the book :(.

Using Socket.IO and Express together

We previously created an Express application. This application is just the foundation. We are going to add features until it is a fully usable app. We currently can serve web pages and respond to HTTP, but now we want to add real-time communication. It’s very fortunate that we just spent most of this chapter learning about Socket.IO; it does just that! Let’s see how we are going to integrate Socket.IO with an Express application.

We are going to use Express and Socket.IO side by side. As I mentioned before, Socket.IO does not use HTTP like a web application. It is event based, not request based. This means that Socket.IO will not interfere with Express routes that we have set up, and that’s a good thing. The bad thing is that we will not have access to all the middleware that we set up for Express in Socket.IO. There are some frameworks that combine these two, but it still has to convert the request from Express into something that Socket.IO can use. I am not trying to knock down these frameworks. They simplify a complex problem and most importantly, they do it well (Sails is a great example of this). Our app, though, is going to keep Socket.IO and Express separated as much as possible with the least number of dependencies. We know that Socket.IO does not need Express, as all our examples have not used Express in any way. This has an added benefit in that we can break off our Socket.IO module and run it as its own application at a future point in time. The other great benefit is that we learn how to do it ourselves.

We need to go into the directory where our Express application is. Make sure that our pacakage.json has all the additional packages for this chapter and run npm install. The first thing we need to do is add our configuration settings.

Adding Socket.IO to the config

We will use the same config file that we created for our Express app. Open up config.js and change the file to what I have done in the following code: Continue reading “Book Preview (Building Scalable Apps with Redis and Node.js)”

Node.js, Socket.io, and Redis: Intermediate Tutorial – React

Download the src(github)
View the demo

Blog Post Series

I want to spend a little time going into React and I felt that this would make the previous a little too long and meandering (almost like this sentence). In this post we will cover what React is, how it is different, what it excels at, how to implement it into a current application, and how to test React views. There is a lot of ground to cover so let’s get started.

What is React

React is a new library for building user interfaces (to steal it directly from their site) developed by Facebook. React is not a full featured JavaScript application framework. This means it is not competing in the same space as Angular, Ember, Backbone or <insert your favorite framework that I am not mentioning here>. It also means it does not care how you route, where you get your data, or any application plumbing. It will render HTML.

Why use React?

Why use React if all it does is render HTML? Continue reading “Node.js, Socket.io, and Redis: Intermediate Tutorial – React”