Share Tweet Reccomend

JavaScript Routing

One of the more important pieces of any client-side JavaScript framework is the routing of requests when users navigate to different places. Basically a JavaScript router in a client-side application will listen for changes in the hash location and update the data and UI in the page accordingly, making all of the API calls that it needs to do so. But how is this feat accomplished? How do we match a route pattern defined in a JavaScript framework to an actual route navigated to by the user? This is something we will look at in what follows.

Normally, when you talk about matching you immediately think to look at regular expressions. However, the way that routes are defined in client side applications often have patterns that are a little bit different that the actual routes that will be navigated to by users. What do we mean by this? We talked about routing in Backbone.js here. Basically a Backbone.js router is set up like the following…

var Router = Backbone.Router.extend({
  routes: {
    "": "home", // url:event that fires
    "new": "createNew"
    "edit/:id": "editItem",
    "download/*anything": "downloadItem"
  },
 
  home: function() {
      alert('We have loaded the home view');
  },
 
  createNew: function() {
     alert('We are going to create something new');
  }
 
  editItem: function(idParam) {
      alert('We are going to edit entry number ' + idParam);
  }
 
});
var router = new Router;

In this setup, when a user navigates to a particular route, the function defined in the routes object will run. So if a user were to navigate to the route #/edit/4, the editItem function will run passing in the id 4.

Read More »

Share Tweet Reccomend

Creating an MVC Express.js Application

Express.js is probably currently the most popular Node.js framework for building web applications and APIs. It has a good history, a good community around it, lots of modules built for it, and a fairly solid reputation.

In what follows we’re going to walk through how to build an Express.js application using the Model View Controller (MVC) design pattern. It’s likely that we’ll do this tutorial in multiple parts.We’ll start out with a simple application structure and then we’ll move on by adding more complex concepts like authentication, dynamic routing, and reading from and writing to a database.

To start, it’s a good idea to have some background on both Node.js and Express so you know some of the terminology and philosophy behind what is being discussed. If you are not entirely familiar with Express.js there is an introduction to it here. And if you’re not entirely familiar with Node.js there is a primer on Node.js here.

At the time of this writing Express is at version 4.X. If you are reading this at a later point, it’s possible that the latest version differs quite significantly from this. Be sure to check out the Express.js homepage to find information on how to properly set things up using the most current version of Express. However, it may be the case that the steps followed in this tutorial will not be fully compatible with the most recent version of Express.js

package.json

To start we’re going to want to create a package.json file. You can read more about pakcage.json here. package.json will define some metadata type things like the name and version of the application, but most importantly, it will specify what modules you will need to download and run the application. You can read more about modules in Node.js here as well as in any good introduction to Node.js. Express is itself a Node.js module and it makes use of other Node.js modules. Some modules like “http” are core Node.js modules (part of the Node.js core) and some like express.js are third-party. Core Node.js modules will always be available to your application because it is running on Node.js

So our sample package.json file will look like the following…

{
    "name": "MVC-Express-Application",
    "description": "An Express.js application using the MVC design pattern...",
    "version": "0.0.1",
    "dependencies": {
        "express": "4.4.4",		
    }
}

One item of note: the name of any given package cannot have any spaces. This is to ensure that installation of packages is easy and consistent across all environments.If people were ever wanting to install our application as a module on npm (if we ever put our application on npm) by running $ npm install MVC-Express-Application it would not work if the package was named MVC Express Application. If we ran $ npm install MVC Express Application, the CLI would get confused.

Now if we run the following from the directory where our package.json file resides

$ npm install

all of the dependencies that we have specified will be downloaded and installed into a “node_modules” directory. The great thing about this is that if we need to update the versions of our modules or add new ones, we can just add or edit this package.json file and run “npm install” again. The npm installer will figure out all of the files needed. We are limited to the modules we are installing right now, but we will be adding a lot more to this later.

Application

Next we’ll want to create an “app.js” file. This file is the kickoff/entry point of our application when it starts up. This is akin to the main() function you’d find in C++ or Java.

The first components we’re going to want to add are here…

var express = require('express');

This loads up the express module. We can now refer to it in our code.

A lot of the modules we’ll be loading up are part of the Express.js project itself. There are many useful items that our application will be utilizing at various times throughout our application. As is described in the Node.js documentation on modules, Node.js modules can be loaded via references to filenames so long as those filenames are not named the same as reserved core Node.js modules, e.g. the “http” module.

Read More »

Share Tweet Reccomend

JavaScript Extend

One of the most important parts of any programming language is the ability to extend objects, creating your own objects and objects that inherit from those objects. In class-based languages like Java or PHP you’ll see the “extends” keyword being used to set up inheritance between different objects.

JavaScript, however, is structured quite a bit different than class-based languages because it is a prototype-based language. For a more detailed look at JavaScript inheritance see this article here. Additionally, opposed to having different types assigned to variables, in JavaScript everything is an object (and, as a result, everything can be extended)
.
In what follows we’ll take a brief look at JavaScript extend functions. Note that this is a little bit different than inheritance. Extend functions in JavaScript could maybe be thought of merging 2 objects, rather than one object inheriting from another. We’ll refer to these as the target object and an extending object. Remember in JavaScript that an object literal is essentially a collection of key/value pairs. Recall too that in JavaScript object keys can also have functions for their values as well. So if a “key” in our extending object already exists on the target object the value for the key in the extending object will overwrite the value for the key in the target object.

The function to extend an object will look something like what is below…

function extend(targetObject, extendingObject){
    for(var key in extendingObject) {
        targetObject[key] = extendingObject[key];
    }
}

Let’s take a look at how this works in practice. Say we have an object called “robot,” that has a couple of properties…

var robot = { 
    size: 'small',
    gas: 100,
    mode: 'helpful',
    move: function() {
        console.log('Walk')
    }
};

Now let’s say we want to extend our robot with some “upgrades”. New properties (keys) will be added to the object and existing properties will overwrite the values for the current object. Will give the robot some more gas (overwriting the robot’s current value), and give it a new mode (setting) and give it a rocket launcher,

var upgrades = {
    gas: 200,
    mode: 'crush kill destroy',
    rocketLauncher: function(){
        console.log('BOOM');
    }
};

Pass this into the extend function…

extend(robot, upgrades);

And now our robot object looks like the following…

var robot = { 

    size: 'small',
    gas: 200,
    mode: 'crush kill destroy',
    move: function() {
        console.log('Walk')
    },
    rocketLauncher: function(){
        console.log('BOOM');
    }
};

Now that we’ve set our robot to “crush kill destroy” it’s a good thing we’ve kept the size at “small.” Hopefully it will be easier to take out if it turns on us.

Let’s take a look at the popular Underscore.js libary’s extend function…

_.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
        if (source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        }
    });
    return obj;
};

Aside from a little bit of conditional checking and variance in how it’s called, the core functional purpose is essentially the same as the function we wrote above.

You’ll often see the extend function used to pass in different options or settings when calling certain jQuery plugins.

$(window).load(function() {
    $('.flexslider').flexslider({
        animation: "slide",
        animationLoop: false,
        itemWidth: 210,
        itemMargin: 5,
        minItems: 2,
        maxItems: 4
    });
});

Within the plugin there will be some default settings, but an object literal can get passed in when calling the jQuery plugin that will overwrite the default settings by using the jQuery extend function. This is an easy way to implement custom settings for a jQuery plugin.

So as we have seen, extend functions in JavaScript are a common and useful way to merge two objects together for a variety of purposes. Hopefully you’ll be able to use this when writing some of your JavaScript based applications.

Share Tweet Reccomend

ECMAScript 6 Classes

At the time of this writing in mid 2014, ECMAScript 6 — which practically in people’s minds means “the next version of JavaScript” — has not been officially released yet and support for its features is inconsistent across different environments. This comes as no surprise as things are still in the works. However, a lot of the features that will be available to developers when the upcoming version finally is released already have a lot of discussion surrounding them. One of these is that there is finally *finally* going to be an implementation of classes introduced into the JavaScript language.

It’s hard not to get excited about the notion of true classes in JavaScript, especially because of what it means for inheritance. We have looked at inheritance in JavaScript previously and how you can kind of mimic class-like behavior by using function objects as constructors and setting the prototypes of inheriting objects to instances of parent objects. However, with classes we will (hopefully), no longer have to worry about this.

Picking up the commonly-used-in-other-languages example of inheritance using animals, let’s see how things might look in ECMAScript 6…

class Animal {

    constructor(){
        this.color = 'brown';
        this.size = 'medium';
        this.age = 1;
    }

    sound() {
        console.log('Grunt');
    }
    move() {
        console.log('Running');
    }
}

class Dog extends Animal {    
    constructor(color, size, age) {
        this.color = color;
        this.size = size;
        this.age = age;
    }

    sound() {
        console.log('Woof');
    }
}

var d = new Dog('Black', 'medium', 5);
console.log(d.size); // medium
d.sound(); // Woof
d.move(); // Running

So as we can see, the inheriting object will inherit items it does not specifically set for itself from the animal object. We can even take this a step further and inherit from Dog. If our constructor formed similarly compares to the object we are inheriting from, we can use the “super” keyword…

class Pomeranian extends Dog{    
    constructor(color, size, age) {
        super(color, size, age)
    }

    sound() {
        console.log('Yap');
    }
}

var p = new Pomeranian('Brown', 'small', 5);
p.sound(); // Yap
p.move(); // Running

How sweet is that? With support for classes it appears that ECMAScript 6 is going to bring about much better implementations of inheritance that follow a more recognizable classical pattern like those seen in Java, PHP, and other languages. It’s something that those who program in JavaScript have been wanting for quite some time.

As mentioned earlier, current support for ECMAScript 6 varies across different environments. One place that you can experiment with some of the new features is this ES6 Fiddle. Classes are just one of the new features on the horizon, but there are other snippets of example code showcasing what else is new in ECMAScript 6 that you can explore,

Share Tweet Reccomend

AJAX and WordPress

When the web moved from HTML4 to HTML5, the rise of AJAX based web applications came along with it. AJAX (which stands for Asynchronous JavaScript and XML) can mean a number of things but in practice it often refers primarily to the client/server interaction where JavaScript can be used to communicate with a server by making calls at various times under various conditions to send and receive data. This can be happening as often as you like in real-time without the user having to navigate to another webpage or refresh their browser (i.e. asynchronously).

AJAX

What is an example of this? Well, say I wanted to put a stock ticker on my webpage or in my web application. I could use JavaScript to make a call to a service like some stock-market API that will give me quotes on a particular stock, get the data back, and display it in the UI in a visually appealing manner. As these market prices update over time, I can periodically update the quotes that I’m displaying on the page. The format that the server returns data in really depends on the service you are calling. It can often be be XML (as the X in AJAX suggests) but another popular format is JSON. I actually like JSON a bit better, myself. The experience of parsing through everything in code just seems a bit cleaner so if there is the option to have the data you are trying to get returned to you in JSON, I’ll usually opt for that.

Because JavaScript is such a universally cross-platform language capable of running on so many different devices in different environments, this can be a great way for different applications to communicate with each other. The result, hopefully, is to give your users the best experience possible whether they are on desktop, mobile, tablet, or some other crazy device.

In the early part of the 21st century, something else that was and has been absolutely ubiquitous across the internet is WordPress. From it’s humble beginnings of being exclusively web-based blog software, it has transformed into essentially the most popular content management system (CMS) used for running small and medium sized websites or web applications.

In what follows, we can look at how we can undertake merging these 2 things together. We’re basically going to look at how we can send and receive JSON data to a WordPress database and read from and write to the tables within WordPress using AJAX.

Read More »