Tyson Lloyd Cadenhead – User Interface Developer

January 23, 2012

A few days ago I realized that I read a lot of books and articles about JavaScript and web development and that this would be a good place to share my thoughts about them both for my own reference and maybe even for helping other people out. In the interest of that revelation, I present to you a quick review of HTML5 for Web Designers by Jeremy Keith of A Book Apart.

The cool thing about this book is that I was able to get it on store credit at McKay, Nashville’s best used book store. If you’ve ever looked for used books on technology, you know that most of them are over ten years old and haven’t been relevant for almost that long, so a modern book like this was a great find.

This is a really easy and quick read. It’s a pretty thin book and I was able to breeze through it in the course of a couple of days. It’s a very basic overview of what you can do with HTML5, so I wouldn’t expect anything as expansive and heavy as the 900 page HTML5 spec, which is probably a good thing considering that it’s not fun or easy to read something that long.

You get a taste of everything from video and audio and their current limitations to the canvas and the new HTML5 input types and attributes. This book made me excited to be in the web development space because there is so much growth happening and there is sure to be a lot more to come soon. It wasn’t terribly heavy on JavaScript, which is always disappointing to me, but there are some examples of how to accomplish backwards compatibility for native HTML5 behavior using my favorite scripting language.

I would recommend this book to any front-end developer wanting to cut their teeth on some more cutting-edge experiences. It made me want to go out and write a JavaScript library to ensure backwards compatibility so we can use more HTML5 form types now, and in my book, anything that makes me want to write JavaScript was worth my time. Unfortunately, that means that everything is worth my time.

December 17, 2011

As a JavaScript developer, I tend to spend a lot of time getting and setting data using a server-side API. Over the past few years, I’ve encountered all sorts of APIs and I’ve formed some opinions on what makes a good API for JavaScript interaction. Here are some of my thoughts.

Make the API use only a single URL, if possible

It’s a pain to keep up with multiple URLs to hit to get different data. Instead of having to hit http://mydomain.com/api/getFoo.php and http://mydomain.com/api/saveFoo.php, I prefer to be able to hit something more like http://mydomain.com/api.php?method=getFoo or http://mydomain.com/api.php?method=saveFoo. I know it’s not that different, but it gets even more complicated when you start passing in IDs as part of the routing structure.

The more that can be passed as query string parameters or post parameters, the better. One benefit of passing params as key / value pairs is that it eliminates confusion, because the purpose of the param should be defined by its name.

Allow multiple data types

Currently, most JavaScript developers prefer to work with JSON because it doesn’t have to be parsed or manipulated and it can literally be used out of the box unlike it’s ugly step-brother XML. The truth of the matter is that we don’t know what the future will hold, so it’s best to abstract the data type to a point where a client-side developer can easily request the one he or she wants by passing it into the request. For example, http://mydomain.com/api?method=getFoo&format=json.

JSONP is a little bit different, because it requires a callback to work. The way I’ve seen this done most effectively is that there is a separate param for the JSONP callback name. For example, http://mydomain.com/api?method=getFoo&format=json&callback=myCallback. JSONP isn’t always needed, but if you are making cross-domain calls, it’s the best we have right now.

Don’t require the method to be GET or POST

POST requests are more appropriate when data is being saved and GET is appropriate for retrieving data, but the decision of which method to use at what time should ultimately be something the client-side developer should be able to chose. A lot of time can be wasted trying to figure out why a param passed in with the query string isn’t working when it is expected to be in the POST scope. Believe me, I know.

Don’t go crazy if unexpected arguments are passed in

A successful API should simply disregard params that are not needed. I’ve seen APIs blow up because I passed in an argument it didn’t expect. In the course of building and maintaining an application, params can get added and removed all the time so the API should be built in such a way that it doesn’t care about arguments that it doesn’t ask for and that it doesn’t care about the order of the arguments that are passed in.

Require as few arguments as possible

In many cases, the only thing that is needed to run a query is a single ID. If that is the case, the request shouldn’t have to be much more complicated than this: http://mydomain.com/api?method=getFoo&format=json&fooid=123

Things can get a little more complicated when the request requires some sort of authentication, but usually that doesn’t require much more effort than passing around an access token.

If authentication is required, only ask for login credentials once

Login credentials should be passed as infrequently as possible to avoid being compromised. The best case scenario is to have an authentication method that passes back a session token that is maintained on the server-side for an allotted amount of time. Once the session token is expired, the user has to log in again. That way, the authentication information such as a username and password are only passed to the server once.

There are definitely more important aspects to creating a successful API, but the basis of most of them are clarity and future-proofing. If the API is easy to change from a server-side perspective and a client-side perspective and everything makes sense, everyone will be happier and the development process will be easier.

October 10, 2011

Most of us can agree that spawning popups with JavaScript is usually a user experience FAIL. We’ve all been to websites that opened several popup ads. That is always something to avoid. Malicious and ad-happy sites have made it necessary for browser plugins and some browsers to block JavaScript popups altogether.

But there are some examples where popups are actually necessary. The main thing to remember when it does become necessary is to make the popup window a response to a user action. Usually a popup should be triggered by a clicking a link or a button rather than opening it on page load. That way the popup is not instantly perceived as an ad and closed by your user.

When using a popup does become necessary and you have exhausted every other options including more attractive modal windows and nothing works for the user interaction, the next concern becomes what to do when the popup is inevitable blocked.

The answer may look very similar to a progressive enhancement technique, but I wouldn’t consider it one since the browsers with a popup blocker enabled are often more advanced than those without.

We’ll start out making a very normal-looking link that targets a blank window to open the site inside of. That should look something like this:

<a href="http://google.com" id="googleLink" target="_blank">Go To Google!</a>

The link will totally work on its own without the aid of JavaScript, it will just open in a new window instead of a popup. Now let’s add the JavaScript. The event listener is written in jQuery, but feel free to rewrite it using your library of choice or none at all.

$('#googleLink').bind('click', function () {
   var popUp = window.open($(this).attr('href'), 'googleWindow',
   'width=600, height=300, scrollbars, resizable');
   if (!popUp || typeof(popUp) === 'undefined') {
      return true;
   } else {
     popUp.focus();
     return false;
   }
});

Popup blockers work by redefining the window.open() function. Part of the beauty of Javascript is that you can redefine literally any variable or object. If you even wanted to redefine the document object or the window object, you actually could. So the popup blockers will typically make the window.open() function return either null or undefined, which means that we can create the popup as a variable and then test to see if the variable actually returns as anything. If it does, we can assume that the popup opened and return false so that the link doesn’t fire off. If it doesn’t, we can return true to let the link do its work.

Here is a working example of the code above:

Go To Google!

As you can see, it’s fairly easy to detect popup blockers and react to them. Be careful with your new-found power. If I haven’t made myself clear, there’s nothing worse than a site with a bunch of popups.

September 23, 2011

In JavaScript, it is often useful to have a place to set and get configuration options. You can do this by just creating an object and updating it, but a global object is less secure because anyone using Firebug can log the object and see the entire thing. A getter / setter gets around that issue because it doesn’t expose any values unless they are specifically requested.

Another advantage of using a getter / setter is that it puts variables inside the local variable scope instead of exposing them to the global variable scope. Keeping the variables in the local scope speeds up the execution of the code because there is less to parse through in the global scope.

So, let’s make a reusable getter / setter class, shall we? Our class should look something like this:


/**
* @class
* @description A reusable class that extends a basic getter / setter
*/
var getterSetter = function () {

   var items = {};

   /**
   * @function
   * @param {String} get
   * @description Gets a param option and returns it
   */
   this.get = function (name) {
      return item[name];
   };

   /**
   * @function
   * @param {String} get
   * @param {Object} value
   * @description Sets a config option
   */
   this.set = function (name, value) {
       item[name] = value;
   };

};

To use the getter / setter we just created, we just need to do something like this:


// Create a new getter/setter called "config"
var config = new getterSetter();

// Set a config item called "myOption"
config.set('myOption', 'This is my option');

// Get the config option (this will alert the message "This is my option")
alert(config.get('myOption'));

There you have it. Now you have a getter / setter that you can use across your entire application.

August 6, 2011

ColdfusionI tend to fall in with Coldfusion programmers from time to time and while I actually really like the language and the community, the one thing that can make working with Coldfusion and JavaScript harder is how the language returns JSON.

Typical JSON looks something like this:


{
   "firstname": "Tyson",
   "lastname": "Cadenhead",
   "favoritelanguage": "JavaScript"
}

But Coldfusion encodes structs to look more like this:


{
    "COLUMNS": ["FIRSTNAME", "LASTNAME", "FAVORITELANGUAGE"],
    "DATA": [[
        "Tyson", "Cadenhead", "JavaScript"
    ]]
}

The problem with that is that JavaScript can’t do much with that. The solution? I wrote a quick and dirty script that parses the Coldfusion JSON into the old-fashioned kind. All you need is this:


Object.prototype.parseCFJSON = function() {

   var result = [],
       data = this;

   for (var j = 0; j < data.DATA.length; j++) {
      result[j] = {};
      for (var i = 0; i < data.COLUMNS.length; i++) {
         result[j][data.COLUMNS[i].toLowerCase()] = data.DATA[j][i];
      }
   }

   return result;
};

If you include that bit of code in your script, anytime you get back a Coldfusion struct, you can simply encode it by running this:

myData = myData.parseCFJSON();

There you go... easy as pie!

Portfolio

See More