Book Review: Principles of Object-Oriented JavaScript

I just finished reading another fantastic resource for JavaScript developers “Principles of Object-Oriented JavaScript” written by Nicholas C. Zakas.

Nicholas C. Zakas is an excellent Front-End developer, and what I have always enjoyed about his work, is his ability to clearly articulate his knowledge to developers of all skill levels. Because of this I had high expectations for reading this book. I’m happy to say that this book did not disappoint.

The book, to me, is an reference I will keep with me throughout my JavaScript career, and I’ll recommend it to any developer interested in JavaScript. Targeted toward JavaScript beginners, this book highlights areas that many who are new to JavaScript will likely have to learn the hard way, or discover after they have reached a level of frustration that makes them decide to hate JavaScript forever.

Now, this does not mean that this book contains some secret recipe to JavaScript Zen, but it does provide all the necessary tools for the reader (Seasoned JavaScripter or one who is new JS) to understand how to build great applications with JavaScript. The topics - functions, objects, prototypes, inheritance - are all covered thoroughly through well though out examples which are not too complex for even a new developer to follow. These examples and explanations are accompanied with wonderful notes and snippets that signal the voice of the seasoned JavaScript professional that Nicholas C. Zakas is. As I wrote above, I definitely recommend this book.

Screencast Debugging in Chrome

Remote debugging a few years ago was just a fledgling idea for most. WEINRE was leading the way with its remote access to mobile devices and worked well enough. In recent posts I have mentioned some improvements across various browsers and new tools that work well for developing and debugging on a mobile device. This area of developer tooling is continually improving and is becoming a more natural fit into a developers workflow.

One of the most recent advancements in remote debugging was announced in early October of this year, but I do not think that until the Chrome Dev Summit in November was it really noticed by a larger audience. This new tool allows you to connect your Android device running Chrome to your computer, Inspect it in dev tools and the chrome experience from the mobile device will be mirrored within the dev tools itself.

To do this, ensure USB debugging is enabled on your device and connect it to your computer. Then on a dev-tools experiments enabled computer navigate to chrome://inspect. You will see your device with any open Chrome tabs listed on this page.
{<1>}
now you will see the inspect link. You should click this and you will get your dev tools open. From here there is a little image that looks like a mobile device (blue in the image below) which will toggle the screencast.
{<2>}Little Blue Phone
Click that and you can now see the screencast of your mobile Chrome experience.
{<3>}Fixie Image

Happy Debugging.

Node.js Recipes

It started when I favorited a tweet in February in which a request was being made for some help updating a JavaScript book. I had recently spent some time contributing to a jQuery Mobile book and wanted to continue writing. Shortly after I contacted Louise (my editor) and it turns out that they had already found someone to update the book…..

It turns out that Louise had some plans for a Node.js Recipes book, which I thought would be spectacular so I set to work writing an outline and proposal for the book.

After a few weeks I had the proposal in hand, sent it to the publisher and it was approved. This is where things get crazy, because I now had to write the twelve chapters I’d outlined and I had less than two weeks to write each one if I was to make my deadline.

This crazy schedule, while good at keeping me on task, was not great at keeping me rested and stress free. There were many late nights and long weekends where I was not able to spend quality time with my family or friends. I am grateful that they allowed me time to research and write, because I was able to create a book which I feel will be a useful tool for any developer who wants to learn more about Node.js. It will give readers a glimpse of what goes on in Node.js not only in the Core, but also in the third-party modules that have helped to create the robust Node.js ecosystem.

If you are interested in getting to know Node.js better, or if you would just like to buy an amazing book for your coffee table or library, please buy the book.

http://www.amazon.com/Node-js-Recipes-A-Problem-Solution-Approach/dp/1430260580/

http://www.apress.com/9781430260585

{<1>}Node.js Recipes

FirefoxOS Apps

A few weeks ago Mozilla announced another initiative to get some more applications into the FirefoxOS Marketplace.

I had submitted a simple compass application early on in the Marketplace’s life, but thought that this opportunity would be perfect to get an PhoneGap wrapped HTML application that I created for Android onto the marketplace, so I applied for a phone for app port deal. Within a couple days I recieved confirmation that I would be getting a developer preview phone from Mozilla, in exchange for my app port.

Now, I could have waited around until I received the phone to get started working, but with the FirefoxOS simulator available as a Firefox Add-On I set to work right away. I had previously submitted an application so I knew the general Firefox manifest format which is probably helpful. Once I had a Firefox app manifest being served (with the proper MIME type) from AppEngine I was ready to submit. I did however wait until I had a physical device to test and ensure it appeared and functioned as I expected.

Busy Times

I have had a busy time over that last few months. Firstly, I have been engaged in a very ambitious and exciting project for my day job.

Aside from this keeping me busy, I also had a talk accepted for the jQuery Conference in Portland in June. This was my first talk at a big technology conference but I think it went well and I hope to do it again.

If you listened to at least the beginning of that talk, you may have heard me mention that I’ve been writing a book. This book has been a great deal of fun, but has also been challenging. Between research, writing code, writing text, editing, and following up with the technical reviewer it has kept me busy. It should be published this fall so stay tuned…

http://www.apress.com/9781430260585

Remote Debugging Revisited

A little less than a year ago, I wrote a post about remote debugging tools. Since that time the landscape has changed, so this post will try update where we are in the world of remote debugging. (Note: by ‘we’, I mean me, and by ‘world’ I really mean, what I’ve used since last year)

First, lets review where we were a year ago. Chrome for Android was brand new, and had remote debugging support baked in. Opera Dragonfly had great remote debugging support. Adobe Shadow (now Edge Inspect) was new, and WEINRE was still a .jar.

Fast forward to now. Chrome for Android still has great remote debugging support, when connected you can see all your inspectable tabs from your remote device, and debug away. In Opera land, things have shifted a bit. Since they have started their switch to Webkit, who knows where their remote debugger will be in another year. Adobe Edge Inspect is a very popular debugging toolset for iOS and Android. Weinre is now (debatably) more accessible as a Node.js server, making it super easy to install and run a local/or remote hosted server. Weinre powers the phonegap debug service . It is also the service behind the experimental mobile debugging option at jsfiddle.net.

The newest version of jsbin.com has a pretty incredible remote rendering capability, but you can see for yourself on youtube:

Over the course of the last year, Firefox has built a homegrown set of Developer tools, so developers need not rely soley on Firebug on Firefox. These tools have been built with remote debugging as a high priority - with the proliferation of Firefox on Android, and the fancy new Firefox OS - remote debugging is important. Remote debugging for Firefox has been around for a few versions, but I really like to live on the nightly branch (currently 22.0a1), so thats what you’ll see here. Its quite simple to enable on your computer: just swing over to ‘about:config’ and toggle ‘devtools.debugger.remote-enabled’ to ‘true’ restart, and you are set.

about config setup

Next (assuming you’ve got your android platform-tools installed) you simply connect your device to your computer and
adb forward tcp:6000 tcp:6000

Then, assuming you have enabled remote debugging on your Android device, you again go to ‘about:config’ and toggle the ‘devtools.debugger.force-local’ to ‘false’ and ‘devtools.debugger.remote-enabled’ to ‘true’.

about config android

Restart. Debug. To Debug you open the remote console by selecting ‘Connect…’ from the Tools > Web Developer menu. Thats it.

Remote debugging is important. And as the web development industry moves more toward mobile, these tools need to and will get better and more accessible for everyone. I expect I’ll be revisiting this topic again soon as tools improve or emerge.

Whitelisting URLs in PhoneGap

I've built a couple of HTML5 (jQuery Mobile) applications that have also targeted native app stores using PhoneGap. When building these applications, it becomes clear that to get desired navigation in iOS, one must carefully consider the PhoneGap settings for url handling "OpenAllWhitelistURLsInWebView" and "ExternalHosts". In many configurations this results in setting the "OpenAllWhitelistURLsInWebView" to "YES" and Subsequently setting a single "ExternalHost" as "*" in order to keep your application functioning within the WebView exclusively. This is great for everything except where you wish to open an external link that would break your HTML5 applications navigation (due to a lack of back button). What follows are a few tricks I have picked up to help with whitelisting. In many cases you know when you're building your application where you'd like to have the external links open, in which case you can set these external links within your Objective-C source code letting the applicaiton know which links to open. This would look something like the following Gist (which looks to the prefix of the URL in order to open a link outside of the WebView):

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if ((navigationType == UIWebViewNavigationTypeLinkClicked) &&
        ([[[request URL] absoluteString] hasPrefix:@"https://www.google.com"])) 
    {
      [[UIApplication sharedApplication] openURL:request.URL];
      return NO;
    }
    return YES;
}

In other cases, your application may allow for some dynamic client created content to come from the server. This can mean either a maintenance nightmare for setting up this prefixed whitelist, where you get to update the whitelist and resubmit the app to Apple everytime the list changes (icky).... Or we can come up with a solution that works better. One way in which this can be accomplished is by looking to the suffix of the URL to find a querystring parameter that would indicate that we need to open external.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  if ((navigationType == UIWebViewNavigationTypeLinkClicked) && ([[url absoluteString] hasSuffix:@"?openExternal=1"] ))
  {
    [[UIApplication sharedApplication] openURL:url];
    return NO;
  
  }
  
  return YES;
}

A perhaps more robust solution, allow for the conversion of any link with target="_blank" to open in Safari. This solution is inspired by this where you tell your iOS app to find a specified document fragment, and also tell your web application to ensure that target="_blank" links always have such a fragment. The Obj-C code looks like this:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
  NSURL *url = [request URL];
  if ( ([url fragment] != NULL) && ([[url fragment] rangeOfString:@"openExternal=true"].location != NSNotFound) )
  {
    if ([[UIApplication sharedApplication] canOpenURL:url]) {
      [[UIApplication sharedApplication] openURL:url];
      return NO;
    }
  }
  return YES;
}

and telling the webapp to set this fragment (using jQuery) looks as follows:

/* turn all target = _blanks into whitelisted urls */
$(document).on("click", function (event) {
  if (event.target.target === "_blank" && event.target.href.indexOf("#openExternal=true") === -1) {
    event.target.href = event.target.href + "#openExternal=true";
  }
});

I read a book: JavaScript Enlightenment

I dunno if this is a full fledged review or not, but I recently picked up and read the new book JavaScript Enlightenment by Cody Lindley, and I found it ranks in my list of JavaScript books I would direct others to read in their quest to JavaScript wizardry. Lindley states he writes his book first and foremost for himself, as a personal reference, which I find handy because that is exactly how I like to read JavaScript books. His approach to teaching the language might strike some as contrary to what is found in the wild - he spends plenty of time not using object literals when creating objects in order to hammer home the underlying principles of JavaScript objects - but he does also hammer home that using literal notation is preferred for its terseness and readability.

What else did I like about this book? Well I enjoyed the use of code examples, as its always good to see JavaScript in action. He also makes many great succinct notes that help make good distinctions such as "Remember: object instances created from constructor functions are just plain old objects". Another concept that those in search of JavaScript enlightenment should find well laid out in "JavaScript Enlightenment" is how the prototype chain is traversed whilst accessing a property on an object. Along with traversing the chain, Lindley describes through an example of what not to do, how prototypes can be altered even on the Object.prototype, promptly reminding the reader that this is a "forbidden" example. Since the prototype is key in JS, the book dedicates a considerable portion to describing and outlining how it all works.

The book describes in great detail and examples many concepts that any front-end engineer should be familiar with. Things such as the Function objects instance properties and methods - you know: arguments, constructor, length, apply(), call(), toString() - including going into specific examples on how to use arguments.callee when calling a function recursively. The discussion of JavaScript scope and closures is straightforward and to the point without over complicating concepts that are sometimes hard for some developers to grasp.

Other parts of this book I would describe as desk reference material. These are items that are common and I think are generally understood by many, but in the case someone runs into a gotcha during development, they may find it useful to hit the chapters on the various objects: Array(), String(), Number(), Boolean(), as well as then utilizing String, Number, and Boolean primitives. Other desk references: Math(), null, and undefined.

I'd totally recommend this book on the same JavaScript binge handed to new developers when the get underway (things like The Good Parts, Eloquent JavaScript, JavaScript Web Applications, or any of the many many useful links to the plethora of great resources available to the modern developer). I guess this did turn into a full fledged review.

Openness

On 11 November 2012, my first patch to jQuery-UI landed in the project. It was not the world's greatest pull request, nor was it the best code ever written (by a long shot).  But it was important. Not because I get my name on a change log somewhere, or that I will now conquer to world with my open source prowess. Its important because it is another tiny step in the massive open source snowball that wins. It wins big. The open web as we know it has spiraled out of openness and open source projects. The documentation that I turn to regularly and have contributed to is open and invites new contributors each day. There are countless open initiatives in the world these days - and by no means are these all software related - these encourage the scientist in us all to submit pull requests, change direction and assert for the greater good. If you have a passion, pursue it. That is all.

Homework

Recently I was tasked by my son's pre-k teacher to present a paragraph that describes my occupation... in a way that 4 year olds will understand. This really put things into perspective for me, more than I thought it would. At first I think of what I might describe to my parents: "Software Engineer: I write code for web applications and databases"... No. So what is it that I do?

I was then reminded of an interview question I once had where I was asked: "How would you describe a database to your grandmother?"  These sorts of questions may seem silly to some developers, but I find them to be a great exercise. These questions help us to target and focus on what it is we really do, and how our end users or clients might perceive what someone in the software profession might be thinking. So I thought of the answer provided in that interview where I made the analogy of a jewelry box that helps to organize and sort jewelry for efficient placement and retrieval.

How does a jewelry box translate to pre kindergarten children? Well I tried to avoid an abstract analogy and simplified it by stating that I teach computers to do neat things and give us information when we ask them for it by typing or clicking the mouse.... Our children don't care about CSS, HTML5, JavaScript, objective-C, C++, Java, Ruby, Python, C#, or if we built our app for Android, iOS, Windows Phone 8 or whatever,
they care if they can learn from and enjoy whatever it is we built.

So a fresh perspective of "how can this actually benefit someone" has been bouncing in my head lately. I'm not saying one shouldn't try new cool tech... Still create experiments and things that push development forward, but perhaps a deeper look at what is truly needed should be a priority.