What are the Best Tutorial Videos for Web Performance?

Web Performance

Learn about web performance from the experts. These videos provide a wealth of knowledge about how to make web pages faster.

Everyone knows what happens when a page loads slowly: the visitor leaves. That much is simple. But what is not always so obvious is what to do when you have addressed the “low-hanging fruit.” There are a number of variables at play with regard to page load time and at times it can be a bit tricky to understand how to measure and analyze each one. In these talks, you’ll find discussions that go beyond CSS sprites and domain sharding. Sure, those techniques (and other similar ones) are almost always helpful, but there is a deeper level of understanding required when trying to get page load speed down to a few seconds. I’ve not attempted to list every helpful video out there; there are many. This list includes the videos that I feel provide the most helpful review of topics. In each case, I’ve found the speaker to have not only a super-expert level of knowledge / experience, but an ability to translate their expertise into an enjoyable presentation.


Optimizing networking performance (and HTTP 2.0) – Crash course on web performance (Fluent 2013)

Ilya Grigorik covers a wide range of topics that define the technology of web performance. There is a healthy percentage of time spent on mobile, including some very deep concepts such as radio optimization and periodic transfers (beacons), and how they consume more battery life than you might expect. One area that is particularly interesting is the TCP/IP “slow start.” Here Ilya explains why the slow start exists (i.e. it’s actually a feature, not a bug), and how it affects performance.


Bandwidth, latency, and radio performance – Crash course on web performance (Fluent 2013)

If you think you understand what happens when you open a web page on your mobile device, think again. Ilya Grigorik goes into incredible detail when explaining what happens in the life of a mobile web request. A highlight is a very helpful explanation of the difference between bandwidth and latency. In addition, he discusses the psychological / business ramifications of delays of more than 300ms. This is a super in-depth talk and very much worth the time if you are interested in the more subtle areas of web performance.


Steve Souders: High Performance Mobile

Web performance guru Steve Souders give a talk that is still every bit as relevant as it was in in 2011. In addition to talking about his famous “14 Rules for Web Performance,” Steve discusses the prevalence of re-directs, domain sharding and the implications of slow JavaScript. In addition, there are discussions about responsive images, app cache, leveraging async JavaScript calls, and downloading JavaScript without executing it (eval alert! : – )


Steve Souders on Web Performance: How Fast Are We Going Now?

One area of this talk that I find interesting is where Steve talks about barackobama.com and how when they improved the speed of the site by 60%, they found that there was a 14% increase in donation conversions. He also talks about trends in connection speeds, performance differences between browsers (including how JavaScript affects this), and his work with HTTP Archive.


Web Performance Testing at YouTube

Rick Viscomi’s high-level discussion or Real User Monitoring (RUM), and Synthetic Testing is fantastic. As a UX engineer at Google/YouTube, his expertise and insights on performance is extremely helpful. Rick explains Google’s approach to client-side instrumentation (CSI), and how their “measure / beacon / analyze” approach works. He also talks about how Google uses WebPageTest for synthetic testing.


Speed Up Your JavaScript

Some may feel that web performance is only about reducing HTTP requests and leveraging CSS sprites, but when you consider that when any external JavaScript file referenced by a script tag is downloaded and parsed, the page is completely blocked. Although this video is more than five years old, it is a must for any JavaScript developer. Nicholas Zakas talks about Scope management, Data access, loops and DOM access in the context of performance. He also does a deep-dive into what actually happens when a function executes and how that affects performance, how the “with” statement and “catch” clause of the try-catch statement affect the scope chain, as well as performance implications of “for”, “while” and “do while.” There is also a discussion of the tricky behavior of HTMLCollection objects, eflow events, and how the DocumentFragment object can help improve performance.


Mobile Web Performance

Guy Podjarny, CTO of Web & Mobile at Akamai gives a great talk about mobile web performance. This video is nearly three years old, but still relevant. Guy’s perspective is particularly helpful because of his work in Akamai and the experience in that domain.


JavaScript: WAT!

JavaScript

JavaScript LogoIf you think JavaScript is an odd language, just wait: a few experiments with the addition operator will really leave you scratching your head

Every now and then, I am reminded that as corny as the term “web surfing” may sound, it is sometimes an amazing experience. Recently, while digressing from a sub-reference of a side-topic that was tangentially related to a random blog post I stumbled across while procrastinating, I found a video titled: “WAT”. If you have even the slightest appreciation for, or hatred of JavaScript, it is a hilarious four minutes.

SPOILER ALERT: Try to watch the video before going any further. It’s much more enjoyable if you don’t know what is coming.

https://www.destroyallsoftware.com/talks/wat

Now that you have (hopefully) watched the video:

I have no idea who Gary Bernhardt is, but he makes some interesting points. Here are a few highlights:

QUESTION: What is the return value of this expression? [] + [];

ANSWER: An empty string

QUESTION: What is the return value of this expression? [] + {};

ANSWER: “[object Object]”

QUESTION: What is the return value of this expression? {} + [];

ANSWER: 0

There are a few more examples, but the overall message is: the JavaScript addition operator produces very odd results in corner cases. I must admit, I’ve never thought to explore this behavior and not only were my answers to all three of the above questions wrong, but I was pretty shocked by the correct answers.

Inspired, I decided to try a few of my own.

Array + Object

While [] + {} does return “[object Object]”, that return value is not an object, but simply a string whose value is: “[object Object]”. To prove this, I did the following:

Array + Function

The return value of this is the exact same thing as foo.toString();

Object + Function

As I tried yet another combination, I started to notice a pattern. When using the typeof operator, the return value was a concatenation of the “toString” methods for each value that was being added. So, if the expression is: {} + foo(), the result is “object” and “true” combined, which is: “objecttrue“. ok, got it.

But the fact that foo + {} returns NaN, makes no sense to me. And then there are a few more adventurous roads one might waddle down:

OK Kevin, so what’s your point?

That’s a fair question. Ultimately, since we never do those kinds of things in our JavaScript code (right? right? : – ), none of this should matter. But as I played around with these examples, two important things came to mind:

Troubleshooting

If you ever replicate these kinds of patterns by accident, it results in the kind of hair-pulling frustration that makes you start to actually believe that there is a dark lord of JavaScript controlling your browser. When trying to track down what seems like unexplainable behavior in your code that is clearly a bug, in addition to that missing semi-colon, implied global, or accidental use of “=” instead of “===”, consider these kinds of patterns. While they all seem very unlikely, typos can happen, and are sometimes hard to spot.

A Deeper Understanding

JavaScript is a truly odd specification. While there are plenty of odd things about it that we do know, there are always a few strange patterns like these that one might not have come across yet. There may or may not be anything useful about all of this, but as JavaScript’s ubiquity and maturity continue, any deep understanding of its quirks and idiosyncrasies can only benefit the developer.

VIDEO LINKS

Jump to: 1:22 for the good parts

(If this video link ever stops working, just google: “A lightning talk by Gary Bernhardt from CodeMash 2012”. There are many pages out there that feature this video)

https://www.youtube.com/watch?v=Othc45WPBhA

https://www.destroyallsoftware.com/talks/wat

 

JavaScript Object Inspection with Object.getOwnPropertyNames

JavaScript

JavaScript LogoWhen you need to get all of the names of an object’s properties as an array of strings, the Object.getOwnPropertyNames method is an excellent tool

In the article: “The JavaScript for…in statement – enumerating object properties,” I discussed the for-in statement as the “go-to” tool for object enumeration. I’m a big fan of that feature and feel it is worth its weight in gold. But I’d be remiss if I did not mention Object.getOwnPropertyNames.

The getOwnPropertyNames method of the “Object” object differs from the for-in statement in two ways: It returns an array, and the elements of that array are strings. These strings are the property names of the specified object.

Example # 1 A

Example # 1 B

In Example # 1 A, we create the object: “userObject”. Then using the Object.getOwnPropertyNames method, we inspect it. Example # 1B accomplishes the same thing, but the results are significantly different because we inspect the window object, and there are literally hundreds of properties. In each case though, the return value of the Object.getOwnPropertyNames method is an array. The array elements are strings that contain the names of each property contained in that object. But what if we want to get the value of each property?

Example # 2

In Example # 2, we use the jQuery.each method to enumerate the elements of the array returned by the Object.getOwnPropertyNames method. Inside the callback, we output not only the name of the property, but the value of that property. The key here is that we use the following syntax: userObject[val]. Since we know the name of the property, we can use bracket notation to get its value (e.g. object[propertyName] ).

Summary

The Object.getOwnPropertyNames method may not always be the right tool for the job. Some may say that the for-in statement is more than sufficient for object enumeration and, often, that may very well be the case. But if you ever need to get all of the names of an object’s properties as an array of strings, the Object.getOwnPropertyNames method is an excellent tool.

Helpful Links for Object.getOwnPropertyNames

http://mdn.beonex.com/en/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames.html

Getting Started with ECMAScript 6 Arrow functions – The “this” keyword

JavaScript

ECMAScript 6 LogoOther than syntax, the biggest change that ECMAScript Arrow Functions brings about, is how it relates to context: in the function body, “this” has a different meaning than you may expect.

It seems to me that the two problems that are solved by ECMAScript 6 Arrow functions are: verbose syntax and the tricky nature of “this” inside a function. Granted, when working with methods and constructors, the meaning of “this” is a bit easier to understand. But when working with functions that are not constructors, or not bound to an object, the “this” keyword will resolve to the window object, and that is rarely the behavior you want. In a function that is defined in the global scope, it is probably unlikely that you will intentionally want to refer to “this” (and global function declarations should really be kept to a minimum or even better, avoided at all costs). But when you have a function that is declared inside of a method for example, it is not at all uncommon to attempt access to “this” from the nested function. This is where the frustration starts, because the meaning of “this” will vary depending on the circumstances.

Example # 1A

In Example # 1A, the object foo has two properties: “color”, whose value is: “red”, and the method: “getColor”. The method foo.getColor has a nested function: privateGetColor, which references “this”. The problem is: inside of privateGetColor, “this” refers to the window object. Since there is no window.color, privateGetColor returns: “undefined”, which means that foo.getColor() returns “undefined”.

Example # 1B

In Example # 1B, we have fixed the situation by creating a private variable named: “me” inside of foo.getColor, which caches “this”. This way, the nested function: “privateGetColor” now has access to “this”, and this foo.getColor returns “red”.

Example # 2

In Example # 2, we have a more elegant solution. By leveraging an arrow function, we no longer need to create the variable “me”, in order to cache the value of “this”. Now that the nested function: privateGetColor is an arrow function, we can reference “this” in the arrow function’s body. Since privateGetColor now returns “red”, foo.getColor() returns “red”.

Lexical binding of “this”

The reason that Example # 2 saves the day, is because of the change in meaning for the “this” keyword inside of an arrow function. Normally, “this” will refer to the object of which the function is a method. With arrow functions, “this” is bound lexically. This means that it is where an arrow function is defined that affects the meaning of “this”, not where it is executed.

Example # 3

In Example # 3, we have an object named “bar”, which has a “color” property. When we execute foo.getColor(), we use the call method to change the context in which getColor is executed. This should have changed the meaning of “this” to “bar”, which would result in the return value of “blue (i.e. privateGetColor.call(bar) should return: “blue”). But that is not what happens; the return value of foo.getColor() is: “red”.

The reason for all of this is that inside of an arrow function, “this” is bound lexically. So, it is where an arrow function is DEFINED, not where it is executed, that determines the meaning of “this”. It might help of think of how scope works in JavaScript. The lexical binding of “this” inside the body of an arrow function behaves in a similar way. The closest containing object outside of the arrow function will be resolved as “this”.

Summary

The meaning of “this” inside an arrow function is without doubt a significant change in the JavaScript specification. Since ECMAScript 6 is 100% backwards-compatible, this has no effect on the meaning of “this” inside of normal function definitions, function expressions, constructors or methods. While it may take a while to get used to this concept, the ramifications are very positive. The ability to reference a specific object inside of a click-handler or AJAX calls makes for code that will be easier to read, manage and extend.

Getting Started with ECMAScript 6 Arrow function Parameters

JavaScript

ECMAScript 6 Logo - arrow functions parametersThere is a tremendous amount of flexibility when it comes to parameters in Arrow Functions.

In the previous article: “Getting Started with ECMAScript 6 Arrow functions – Basic Syntax,” we had a very basic overview of ECMAScript 6’s Arrow Functions and their syntax. In this article, I’ll dive a little deeper into the topic of parameter.

In the previous article, we learned how the parameter(s) now come first, and then the “=>” characters, which effectively replace the “function” keyword. This is very efficient and is a key aspect to the simplicity of arrow functions. But it won’t take long before you’ll want to accept multiple parameters in your arrow function. And of course, you may want to accept no parameters.

Example # 1

In Example # 1, the function addTwoNumbers accepts two parameters. This differs from all of the examples in the previous article, each of which dealt with only one parameter. In ECMAScript 6’s arrow function, when you need to accept multiple parameters, you leverage syntax which should be quite familiar to you: enclose the parameters in parentheses.

Arrow Functions that Take No Parameters

In situations in which you’ll want to accept no parameters, the syntax will be empty parentheses.

Example # 2

In Example # 2, we have the function: returnHello. This function takes no parameters and simply returns the string: “hello”. It is certainly not a very useful function, but the main point here is that if you need to create an arrow function that takes no parameters, simply use a set of empty parentheses in place of what would have been a single parameter or parentheses that contained multiple parameters.

The Arguments Object

According to the ECMAScript Language Specification ECMA-262 6th Edition – DRAFT, “Arrow functions never have an arguments objects.” At the time of this writing, version 33.1 of FireFox does allow access to the arguments object inside of an arrow function.

Example # 3

Running Example # 3 in the JavaScript console of FireFox 33.1 demonstrates that the argument object is, in fact, available inside of an arrow function. I’m not sure if this is a mistake or an intentional disregard for the specification. For now, it’s probably best to not attempt access to the arguments object inside of an arrow function.

Summary

In this article we talked about parameters in ECMAScript 6 Arrow Functions. We discussed how to accepts multiple parameters, as well as how to specify none. We also talked a bit about access to the arguments object inside an arrow function. In the next article, I will discuss the value of “this” inside an arrow function.

Getting Started with ECMAScript 6 Arrow functions – Basic Syntax

JavaScript

ECMAScript 6 Logo - arrow function syntaxArrow functions provide a terse syntax, making for code that is more concise and flexible.

One of the most significant features of the ECMAScript 6 specification is arrow functions. Also referred to sometimes as “fat functions,” this change radically alters the rules with regard to functions in JavaScript. Initially, I had planned on writing an “Introduction to / Overview” article about arrow functions. But since code samples are always helpful, I didn’t want an “Overview” article that had code examples for every aspect of arrow functions. Instead, I decided to just jump in, and create an article that focuses on each area of importance. So this article provides a very simple introduction to general arrow function syntax.

Perhaps the hardest part to get used to with regard to ECMAScript 6 arrow function syntax is the fact that the “function” keyword and parameters are reversed. In addition, the “function” keyword is replaced by: “=>”. So, the end result is:

The above example is pseudo code, but my intention was to demonstrate the correct syntax for arrow functions. So let’s look at a working example:

Example # 1A

 Example # 1B

In Example # 1A, we have the standard syntax you would use when creating an anonymous function expression. That is, the function “addOne” takes a single parameter (a number), and returns that number plus one.

Now in Example # 1B, we have accomplished the exact same result, using arrow function syntax. The “var addOne =” portion of the code should be familiar to you. But it’s after the assignment operator, that things start to look quite different. First, we next have the single parameter: “someNumber”. That parameter is followed by: “=>”. This equal+greater than character combination replaces the “function” keyword. Next we have the function body.

The Function Body

In Example # 1B, you may have noticed the absence of the curly braces. This is because the body of our arrow function consisted of one expression. In this case, the curly braces can be omitted. When the arrow function consists of more than one expression, then curly braces are required. Also, when the function body consists of a single expression, the implicit return value of the function is the result of that expression. This is why the return value of our arrow function is the passed-in parameter plus one, even though there is no “return” statement.

Example # 2 A

Example # 2 B

 

In Example # 2A, the return value of addOne(2) is: “undefined”. This happens because the function body of addOne has curly braces, but we have not explicitly returned a value. So, just as with any function in JavaScript, a function that does not specify a return value returns “undefined” (the exception to this rule is a constructor function, which can return any object but returns the instance object when no return value is specified).

In Example # 2B, we get the expected behaviour because we specify a return value.

Returning an Object in a Single-Expression Function Body

One of the main benefits of arrow function is the terse syntax. While multi-expression function bodies are perfectly acceptable, it is likely that in many cases, you’ll want to leverage that streamline single-expression (hence single-line) syntax. But what if you want to return an object in this scenario? Since the curly braces can be omitted, you simply need to wrap the object you return in parentheses.

Example # 3

In Example # 3, we’ve gone back to a single-line version of the addOne arrow function. What differs here is that the function body is wrapped in a set of parentheses. Inside of these parentheses is an object. The beauty of this approach is that the single-line version of arrow functions allows you to omit the “return” statement, so we just provide the object that we want to return in the parentheses.

Summary

This article merely scratches the surface of what is possible in ECMAScript 6 Arrow functions. But the goal here was to simply provide a gentle introduction to the syntax. The biggest changes you’ll notice right away are:

  • The order of the parameter(s) and the “function” keyword are switched.
  • The “function” keyword has been replaced by: “=>”.
  • When the function body has a single expression, no curly braces are required.
  • When the function body has a single expression, the implied return value is the expression.
  • When the function body has a single expression, an object can be implicitly returned if it is wrapped in parentheses.

In my next post, I’ll dive a bit deeper into Arrow Function parameters.

Helpful Links for ECMAScript 6 Arrow functions

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

http://wiki.ecmascript.org/doku.php?id=harmony:arrow_function_syntax

http://people.mozilla.org/~jorendorff/es6-draft.html#sec-arrow-function-definitions

Emulating a Mobile Device in FireFox

Mobile

Modify Headers Logo

Resizing your browser down to 320px doesn’t always do the trick. If you prefer to develop in FireFox, but need to emulate a mobile experience, the Modify Headers add-on is very helpful

This past week, I’ve been developing an optimizely experiment for a new client. This has been one of the more ambitious experiments I’ve developed. It requires not only a complex reworking of an existing slideshow, but back-end reporting on the user’s choices, form submission and exit point as well. But the most significant challenge has been the fact that there is no dedicated mobile URL for this site. Device detection is done on the back-end, and then either the desktop or mobile version of the page is served.

cnn.com before using Modify Headers
cnn.com in desktop FireFox before using Modify Headers

There were a few obvious options that first came to mind. I knew I could leverage Safari to view the page on my iPhone and yet have complete control of the DOM via the JavaScript console. But that is mainly useful for previewing my work and interacting with the DOM through the console. Given the amount of work ahead of me, I preferred to work in a desktop browser. Also, Google Chrome’s Device Mode Mobile Emulation is awesome, especially for testing mobile-specific gestures. But I still prefer to do my front-end development in FireFox. The main reason for this is that even though FireFox has become possibly the slowest browser and always feels painfully sluggish, I still prefer FireBug over Chrome’s built-in developer tools. I cannot stress enough, how outstanding Chrome’s developer tools are, and how much they are improving every day. But when it comes to the first 90% of the general development grunt-work, FireBug’s CSS panel and JavaScript console just always feel more natural to me.

cnn.com before using Modify Headers
cnn.com in desktop FireFox AFTER using Modify Headers

Coincidentally, I also just checked out FireFox Developer Edition. Now while it clearly had some pretty cool features, I wasn’t getting what I needed quickly (and to be fair, this may be purely due to my inexperience with the new FireFox developer edition).

Nearly exasperated, I thought to myself: “Wait a minute, there has to be a plugin that lets me spoof the headers…” After about 7 seconds with Google search, I came across  Modify Headers 0.7.1.1 by Gareth Hunt. Problem solved. In less than five minutes, I had successfully forced the site to serve-up it’s mobile version in my desktop’s FireFox browser. I quickly re-sized the browser down to 320px (or as close as FF would allow me to get to that). I then set my FireBug location to “detached”, and set these two windows side-by-side.

The Modify Headers add-on is simple and easy to use. By default, it appears in a new window, but can also be set to appear in a new tab via the options pane. You can add new headers or override existing ones (e.g. Accept, User-Agent, Cache-Control, etc.). Without the use of a manual, it is easy to figure out how to save and edit headers, as well as change their order. What I liked most about this add-on is that the features are few, it’s easy to configure, and it just works.

Summary

There are multiple options when it comes to emulating a mobile device in a desktop browser. Safari’s user-agent spoofing is quite helpful, Google Chrome’s Device Mode Mobile Emulation Emulation feature is simply outstanding, and FireFox Developer Edition shows great promise. Choosing the right tool depends on your needs. I prefer to do as much of my front-end grunt-work as possible in FireFox because I still work faster when using FireBug. But many prefer Google Webmaster Tools. Because of my preference for FireBug, I found Gareth Hunt’s Modify Headers 0.7.1.1 to be the tool that solved my problem. If you also prefer to work in FireFox, then I recommend this add-on. If FireFox is not your development browser of choice, then I hope you will find some of the below links helpful.

Helpful Links for mobile development in a desktop browser

Modify Headers 0.7.1.1
https://addons.mozilla.org/en-US/firefox/addon/modify-headers

http://www.garethhunt.com/modifyheaders/

Device Mode Mobile Emulation – Google Chrome

Using Safari for iPhone, iPad and iPod Touch Website Testing
http://www.htmlgoodies.com/beyond/webmaster/toolbox/article.php/3889011/Using-Safari-for-iPhone-iPad-and-iPod-Touch-Website-Testing.htm

FireFox Developer Edition

https://www.mozilla.org/en-US/firefox/developer/

Formatting Code Samples in a Google Docs Document

JavaScript

Formatting code in Google Docs

If you are formatting code samples for your Google Docs document, there is an odd little tool that you might find quite helpful.

I recently worked on a project for a client that required adding JavaScript code samples to the documentation. At first I made a very bad assumption that there was no way for formatting code in a Google Document, so I started out using images of code samples. What a waste of time. Finally, it occurred to me that this must be a common challenge.

It turns out that there are two tools available: “Code Pretty,” and “Online syntax highlighter like TextMate.”

OPTION # 1: Online syntax highlighter like TextMate

Formattig CodeThere is an odd little tool called: “Online syntax highlighter like TextMate.” At first glance, this page might appear incomplete, if not broken. It is interestingly un-styled and bare-bones. But here is the thing: this tool is actually pretty awesome. Just paste your code snippet in, choose from one of the many supported languages, then click the “Highlight” button. You wind up with two things: raw HTML and formatted text. The HTML is perfect if you need markup. Copy and paste this formatted text into a Google Docs document. The final impressive feature is the “Style” drop-down. There are about 20 different themes to choose from. For example,  an example of formatted code generated with the Online syntax highlighter like TextMate tool is to the left.

Link for Online syntax highlighter like TextMate: http://markup.su/highlighter/

OPTION # 2: Code Pretty

Code Pretty is not bad. After a super-easy Chrome install, I was fortunately able to format code blocks quickly and easily. There are however,  clearly some drawbacks to Code Pretty.

Unfortunately, the only formatting option is font-size.  Also after a while, Code Pretty generated repeated messages saying that too many calls were being made to the service

Ultimately, Code Pretty simply stopped working. After a while it was functional again, but there is no pattern to the issue. Therefore this is not a recommended application.

Installation Link for Code Pretty:  https://chrome.google.com/webstore/detail/code-pretty/igjbncgfgnfpbnifnnlcmjfbnidkndnh?hl=en

Summary

Code Pretty” is good, but has issues and a limited feature-set. On the whole,  “Online syntax highlighter like TextMate” is an oddly-named, yet super-useful tool that is otherwise perfect for use with Google Docs documents.

Helpful Links

https://docs.google.com

http://markup.su/highlighter/

Better JavaScript Alerts with SweetAlert

JavaScript

From time to time, you may actually need an alert-like user experience. When you do, SweetAlert beats the built-in JavaScript alert function hands down.

I think most would admit that the alert was one of your first “JavaScript moments.” Or at least, it is how you debugged your very first JavaScript project. If you are a member of neither group, then you get to pick from the treasure chest on the way out. Regardless, the alert function is one that, from time to time, may be what you want… at least in spirit. More likely, you will want to use the built-in confirm functionality to act upon a “yes / no” user response. If you find yourself actually considering using or imitating the alert or confirm functions, consider SweetAlert from Tristan Edwards.

SweetAlert isn’t a jQuery plugin. Instead, it is a combination of one JavaScript file, some CSS and a handful of images. Together, they produce an alert / confirm UX that is highly-configurable and pretty serious eye-candy. Implementation is super-simple, using the global “swal” method.

Examples

A fancy JavaScript alert

A JavaScript alert with a custom icon

You can definitely do better than alert-like messages though. When you wander into confirm territory, you can customize the yes/no experience, and even provide a callback to inform that user that something they agreed to do completed successfully. I won’t try to replicate the SweetAlert examples here because Tristan Edwards already does an excellent job of that. My only message here is: If you need a better JavaScript alert/confirm experience, consider SweetAlert!

The SweetAlert Home Page: http://tristanedwards.me/sweetalert

SweetAlert on GitHub: https://github.com/t4t5/sweetalert

Two thumbs up for JSCritic.com

JavaScript Tools

JavaScript Logo

Cleaner code is always critical. When you are staring at an empty text file, using online tools such as jslint.com and jshint.com is pretty easy. But when your code grows to hundreds or even thousands of lines, constantly copy/pasting the entire contents of your JS file into these tools gets tedious. Some text-editors have great plugins that incorporate linting into your development environment, that that is often a great way to go.

But what if you simply want to do a quick “dummy-check” ?

I just stumbled across jscritic.com by Juriy Zaytsev and found it to be quite helpful for just that purpose.

The sub-title of this tool is: “Quickly check how well 3rd party script behaves.” That promise is kept by the following features:

  • Does it browser sniff?
  • Does it extend native objects?
  • Does it use document.write?
  • Does it use eval?
  • Does it use ES6 features?
  • Does it use Mozilla-only features?
  • Does it have IE incompatibilities?

But it is was these tools that really impressed me:

  • How many global variables?
  • How many unused variables?
  • Total size KB
  • Minified size

The first time I visited JSCritic.com, I quickly dumped the script I was working on into it and found out that I had a few un-intended implied globals and plenty of unused variables. The total “Total size KB” and “Minified size” are also helpful in terms of getting a quick idea of your script’s overall footprint. A quick look at Juriy Zaytsev’s blog and you can see he’s a serious JavaScript developer. I’m looking forward to reading his articles. In the meantime, I’m making good use of his tool: JSCritic.com.

Helpful Links

jscritic.com
perfectionkills.com

Video – Back-End vs Front-End Web Programming Languages

Videos

The main difference between a back-end and a front-end web programming language is where the code is executed. In this video, I demonstrate how a back-end programming language is executed on the server, whereas a front-end web programming language is executed in the browser.

Read the Full Post: What is the difference between a back end and a front end web programming language?

Back-End Programming Languages

While there are certainly a number of back-end web programming languages, for this video I use PHP. I demonstrate who the server escapes the opening / closing PHP tags and executes whatever code is inside of them. I’ll also show you how the client can send a message to the web server in order to dynamically alter the HTML that is served.

Front-End Programming Languages

The list here is pretty short: JavaScript. Every modern web browser understands JavaScript. In this video I demonstrate how JavaScript is executed on the client-side (i.e. in the browser). I show you how JavaScript code is delivered from the server, but executed on the client. I’l also show you how to run arbitrary JavaScript code in the client using The FireFox plugin: FireBug.

Getting Started with Backbone.js Models – Part II : Creating an Initialize Method

Backbone

Backbone.js LogoIn the previous post: “Getting Started with Backbone.js Models – Introduction,” I discussed how the extend method of the Backbone.Model constructor is extended, which results in a new “class” that you can instantiate. When extending this constructor, an object was passed-in, which contained default values for the model data. Those default values were key/value pairs that were contained in the “defaults” property of the passed-in object.

In this post, we will talk about a sibling the of “defaults” property: the “Initialize” method.

The “Initialize” method

Why would we care about an Initialization method? Single page applications require an intimate relationship with the data. Not only do you consume and present data, but in many cases, you will want to know when a Backbone model is created or changed. Adding an “Initialize” method to your Backbone model allows you to interact with your model at the time of creation.

Why would I need an “Initialize” method?

While there are many answers to that question, a fairly typical one would be: “notification.” Let’s say that your single page application (aka “spa”), consumes a list of salespeople who work for a company, and presents that list in the DOM. If the application allows the user to create a new salesperson, then you would likely want to update the DOM, adding the new salesperson to the list. The most logical way to accomplish this is to have a method attached to your model that executes when a new instance is created (i.e. when the model constructor is instantiated), and that initialize method would update the DOM, possibly even presenting the data from this new model.

NOTE: In order to keep the code examples here short and simple, I will only present code that has changed since the last post. For the base code that is behind the working example below, view the page source as well as the link to the JavaScript file.

Example # 1A

Example # 1B

In Example # 1A, we have a quick re-cap of or SalesPerson Backbone model from the previous post. As discussed, we extend the Backbone.Model constructor, passing-in an object with a “defaults” property, which contains key/value pairs that supply default data values (e.g. “John” and “Smith”).

In Example # 1B, we have added a method named: “Initialize”. This method is executed when the model is instantiated. This means that every time we create a new model, that model’s “Initialize” method will execute. In this example, a message is logged to the console, which includes the “fname” and “lname” properties.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1B: http://jsfiddle.net/y5j7G/

(be sure to open your JavaScript console when you view the JS Fiddle link above)

Example # 2

 

 

In Example # 2, we have the actual code from the full working example (link below). The reason for the setTimeout is to exaggerate the “message” effect. Since things happen pretty quickly, I wanted to make it a bit easier to see that when a new model is created, that model’s “initialize” method executes.

HERE IS THE LINK TO THIS ARTICLE’S FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/backbone/models/basics/html/part-ii.html

How to Demo:

Each time a new SalesPerson item is created, a green message flashes in the upper-left-hand corner of the browser. When the page loads, there are four such messages. As you manually add new SalesPerson items, a green message will flash, showing the model data. All of this is made possible by the SalesPerson constructor’s initialize method.

Summary

In this post, we learned how to create an initialize method for a Backbone Model. We discussed why this is important, and how it can be used in a real-world context.

Helpful Links for Backbone Model’s initialize method

http://stackoverflow.com/questions/10118988/whats-the-difference-between-initialize-and-constructor-on-a-backbone-model

http://vairix.com/blog/backbone-initialize

Getting Started with Backbone.js Models – Introduction

Backbone

Backbone.js LogoLearn how Backbone.js Models provide abstraction that simplifies data management in your single page application

In my previous articles about Backbone.js, I covered the basics of routes and views. I chose those areas as starting points because they are a bit easier to digest and put to use. For example, you can put together simple pages that demonstrate routes and views. To me, these are “quick wins.”

But data is where the real action is. The whole point of a single page application (aka “spa”), is that the page loads, you pull in data, display the data, possibly allow the user to change some of the data, and update the page accordingly. If there is no data in the mix, it’s just a static web page. Even in that scenario, Backbone routes and views can be very helpful because they force you to organize your code so that it is easy to read, manage and extend. But when you need to consume, display and manage data, Backbone really shines.

Why Backbone Models?

Well, in short: Backbone Models wrap your data with super-useful functionality, providing time-saving abstraction.

What?

Ok, consider the following data:

Now, that all seems nice. But what if you needed to run a function as soon as that object is created? You would need to write a function that “creates” the object first, and then calls a callback (a typical approach). Ok, but now what if you wanted to have a function that was executed any time that the data changes? Well, then you would need a “setter” method, that… yep…. calls a callback. And then what about if the “setter” method had to return only the data that was changed? Oh yeah, and it has to return the previous value of any changed data as well. This is more than a few lines of code.

Now, what if you realized that a giant e-commerce app you are building will probably need all of that functionality, but there will be different kinds of data and you will probably need even more data management tools

All of this (and more) has already been done for you: Backbone.js Models.

Example # 1

In Example # 1, we have created a variable named “salesperson”. As a result, this variable becomes a constructor function. (If you are not familiar with the concept of JavaScript constructor functions, you might want to review this article: What is the difference between an Object Literal and an Instance Object in JavaScript ? | Kevin Chisholm – Blog )

It is important to understand that you are “extending” the Backbone Model “class”. This means that you are creating a constructor function that inherits from the Backbone Model constructor. You will never execute your SalesPerson constructor. In other words, you will never do this:

You will instantiate that constructor in this manner:

In this scenario, “someVariable” becomes an “instance” of the SalesPerson constructor, which inherits from the Backbone Model constructor. So far we have not added any new functionality to our “sub-class” of the SalesPerson constructor, which means that it is virtually identical to the Model constructor. Let’s change that.

Example # 2A

In Example # 2A, we passed an object into the extend method of the Backbone.Model constructor. This is where we start to see some value in our efforts to sub-class this constructor. This object tells the extend method: “Hey, give me the Backbone.Model “class” but add the properties and methods that I provide in this object.

The “defaults” property is a big first step. What you are doing with that property is proving values for all of the properties that EVERY instance of the SalesPerson will constructor will have. In most cases, you will want to overwrite those properties (i.e. there is not too much use in having 700 data objects with the same “fname” of “John”. This approach makes more sense with properties like “totalSales” or “title”. These are the kinds of values that can have a default, and then on a per-item basis, when appropriate, a specific value can be provided.

Example # 2B

In Example # 2B, we have instantiated our new SalesPerson constructor three times. The first two instances: “tom” and “andy” provide all three properties that our Backbone Model expects: “fname”, “lname” and “totalSales”. But you might have noticed that the third instance: “jane”, does not provide a “totalSales” property when instantiated, which means that the default value of “$0” will be used.

Example # 3

In Example # 3, we have the full JavaScript code for our working example.

DISCLAIMER: There are a number of JavaScript anti-patterns here. I wanted to keep things simple here so please disregard the fact that there are multiple global variables, an overall lack of names-spaced methods, and no client-side templating is used.

First we have a variable named: myJsonData, which simply provides the raw data. We then have our SalesPerson constructor, which extends Backbone.Model, and has default values of “John”, “Smith” and “$0” for the properties “fnam”, “lname” and “totalSales”. We then instantiate the SalesPerson constructor four times, creating instances, which are each Backbone models (i.e. “tom”, “andy”, “jane” and “kendall”).

The variable: “isNewItem” simply provides a way to give any user-created LI elements a different appearance.

The function: “makeLi” takes a Backbone model instance and uses its “get” method to get a property value from the model. That function returns a jQuery object (i.e. an LI DOM element wrapped with jQuery).

The function: renderInitialSalesData passes our four Backbone model instances to the makeLi function, and injects them into the DOM.

Finally, we create a click-handler for the ‘#addModelSubmit” button. This handles the form submit so that the user can add a new Sales Person. On each click, the “First Name”, “Last Name” and “Total Sales” values from the form fields are passed to a new instance of a Backbone model, and then injected into the DOM.

HERE IS THE LINK FOR FULL WORKING EXAMPLE: http://examples.kevinchisholm.com/backbone/models/basics/html/part-i.html

HERE is the JAVASCRIPT: http://examples.kevinchisholm.com/backbone/models/basics/js/part-i.js

How to Demo:

When the page loads, you’ll notice that there are three items rendered in the DOM. The data for these elements comes from the global variable: myJsonData.

After page load, enter “First Name”, “Last Name” and “Total Sales” values from the form fields, and then click: “Add New Sales Person”. Each time you do so, a new LI is injected into the DOM, using whatever values you entered. Notice that for any field you leave blank, the default value defined in our model constructor is used (i.e. “John”, “Smith”, and “0”).

Summary

In this article we were introduced to Backbone.js Models. We talked about the value that they provide, and main reasons for using them. We learned how to extend the Backbone.Model constructor, add default properties to the new sub-classed constructor, and then instantiate it.

There is much much more to talk about with regards to Backbone.js models. This article barely scratched the surface, but I hope it has been a helpful introduction to the topic.

Helpful Links for Backbone.js models

http://backbonetutorials.com/what-is-a-model/

http://www.codebeerstartups.com/2012/12/3-defining-models-in-backbone-js-learning-backbone-js

Getting started with Mustache.js now available on learnable.com

JavaScript-Templating

Learnable LogoIn my first screencast with Learnable, I cover the basics of Mustache.js, a popular client-side JavaScript templating library.

A Subsidiary of the well-known SitePoint brand, Learnable.com has been an independent course platform since 2010. They have a catalog of over 4,000 videos, covering a wide range of technology-specific topics. Learnable’s web site is well organized and easy to navigate. They work with highly-respected professionals who create short videos and long-form courses. The content is top-notch and well-produced.

Mustache LogoIn this video, I cover the basics of Mustache.js. You’ll learn how to include mustache.js in your web page, creating HTML templates, rendering an HTML template with data, as well as rendering a list of values in a template. There are code-examples included with the video as well, in case you want to follow-along and edit the code as you watch.

Here is a link to the Learnable.com Video Page: https://learnable.com/hub/play/79

Many Thanks to Erica Wass and Angela Molina from Learnable for so much help in making this first screencast a success!

 

When did Walmart become so hip?

Node.js

WalmartLabs LogoWalmartLabs is doing some very cool things with Node.js. When the heck did all this happen?

Did you know that Walmart supports nearly 30 open-source modules, most of which are used in production, or that they created their own “private npm” to prevent hacks? Nope, neither did I.

I must admit, Walmart is not a company that comes to mind when I think of leading-edge web development. But like many older large-scale organizations, they have realized that they need to better leverage technology, or lose market share to companies such as Amazon. Well, it sure seems like they are very focused.

I had never heard of WalmartLabs until very recently. I kept noticing that in my Node.js-specific web-surfing, their name started to pop-up. So I took a look, and what I found was impressive.

It seems to me that Walmart has been hiring top engineering talent, and putting them to good use. They are doing some pretty cool stuff with Node and making serious contributions to the open-source community. Below are two videos I have recently viewed that are very much worth checking out. If you are interested in Node.js in the enterprise, these folks have a lot to share.

Cheerios and Fruit Loops: Frontend Node At Walmart by Kevin Decker

Walmart Senior Mobile Web Architect Kevin Decker talks about how Walmart threw out their legacy Java stack, and the many challenges of SPAs. In particular, he provides an in-depth discussion on pre-caching with Phantom.js, Thorax, the Cheerios Library, Fruit Loops (“a sugary cheerios) and Contextify.

Node.js at Walmart

Walmart Sr. Architect Eran Hammer talks about the server stack that they built on smartOs, hapi – their open-source Node framework, and custom “server partials”. He also discusses their use of Node as an orchestration layer, and some of the challenges of migrating from their legacy Java back-end.

http://nodejs.org/video/

Interesting Links related to WallmarLabs

http://www.walmartlabs.com/

https://github.com/walmartlabs

http://en.wikipedia.org/wiki/@WalmartLabs

http://www.walmartlabs.com/the-blog/

http://techcrunch.com/tag/walmartlabs/

Getting Started with Backbone.js Views – Part III : Event Handlers Basics

Backbone

Backbone.js LogoLearn how to set up event handlers in your Backbone.js view

In the previous two articles of this series: “Getting Started with Backbone.js Views” (Parts I & II), we learned how to set up a view and optimize it for better performance. The next logical step is event handlers.

While it may be possible that your view will not be interactive, it’s difficult to imagine a mature application that does not involve event handlers. Backbone’s approach to event handlers is a bit of a departure from your standard document.addEventListener and jQuery.click methods. Here, you will add an “events” property to the object that is passed into the Backbone.View.extend method. That “events” property is an object whose key-value pairs are sets strings comprised of an event/selector and event handler.

Example # 1A

In Example # 1A we have instantiated the MessageView constructor. Implementation details of our Backbone.js router are not at all the focus of this article, but I wanted to point out that when setting up event handlers in a Backbone view, it is important to pass an object to the view constructor. In that object, we have specified an “el” property, whose value is a jQuery DOM object. The reason for this is that it allows Backbone to properly attach our event handlers and then tear down the views DOM elements change.

Example # 1B

In Example # 1B we have added an “events” property to the object that is passed into the Backbone.View.extend method. This property is an object. In this example, that object has one property. The property name is a string that consists of two parts: the name of the event, followed by a CSS selector that identifies the DOM element to be targeted. In this case, the “click” event is specified, and the following CSS selector targets the element: “.messageView.mainMessage p”. Again, that is the key or property name. The value of that property is: “clickHandler“, the name of the function that will handle the event. This example is not very exciting. When the target element is clicked an alert shows the message: ‘I was clicked!’. We can do better.

Example # 1C

In Example # 1C, we inject the message: “I was clicked” into the DOM, a step up from the alert, but still not too sophisticated. We’ll clean this up in Example # 3.

Example # 2

In Example # 2, we have added two more properties to the “events” object: mouseover and mouseout event handlers. The purpose of this example is to illustrate that you can specify as many event handlers as you need in your “events” object.

Obtaining a Reference to the Target Element

Example # 3

In Example # 3, we have set up some functionality that is a bit of an improvement over the alert in Example # 1. Each time you click the message, timestamp is injected into the page.

You’ll notice that we are using a function named: “renderTimestamp”. This function is defined in the HTML file. Its implementation details are not particularly important. Suffice to say that when passed a jQuery DOM element object, it injects a time-stamped child element. The purpose of this is simply to demonstrate that we have real-time access to whichever DOM element is the target of an event.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://examples.kevinchisholm.com/backbone/views/basics/html/part-iii.html

How to Demo:

When the page loads, you will see the default route. If you click “message/hello” or “message/goodbye”, you’ll see our custom routes in action. In either case, the message text has a click handler attached to it.

When you click the message text, you will see a time-stamp injected into the page. No matter how many times you click the message a new time-stamp will be added. When you mouse-over any time-stamp, the background color of that time-stamp will change.

Summary

In this article we learned the basics of how to set up event handlers in a Backbone.js view. We discussed how to specify the “el” property for a view, and then create an “Events” object. We also covered how to configure multiple events, as well as how to reference the target element and manipulate it.

Helpful Links for Backbone.js View Events

http://www.codebeerstartups.com/2012/12/12-listening-to-dom-events-in-backbone-js-learning-backbone-js

http://kevinhamiltonsmith.com/backbone-js-view-dom-events-complete-list/

http://lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/

Getting Started with Backbone.js Views – Part II : Optimization Basics

Backbone

Backbone.js LogoiLearn how to optimize your Backbone.js view for better performance

In the first part of this series:  Getting Started with Backbone.js Views – Part I : Introduction, we learned the basics of how to implement a view in Backbone.js. Although the process of extending the Backbone.View class was quite similar to extending the Backbone.Route constructor, our code was not efficient. There are two areas to address: 1) Multiple constructor instantiations, and 2) Separation of presentation and data.

Multiple constructor instantiations

Example # 1A

In Example # 1A, we have the “message” method that is meant to handle any request to the “#/message/:text” route. While this method works as intended, we instantiate the the “MessageView” class each and every time that route is requested. There is no reason to instantiate that class more than once, and from a performance standpoint, this code is inefficient.

Example # 1B

In Example # 1B, we’ve fixed the instantiation problem by leveraging the “initialize” method. If you remember from the article: “Getting Started with Backbone.js Routes – Part IV: Configuring an Initialization Function”, the “initialize” method only executes once. This is a perfect place to handle setup tasks for views. In Example # 1B, we instantiate the “MessageView” constructor. But, instead of assigning the newly instantiated object to a variable, we assign it to “this”, which is the instance of the “AppRouter” constructor. The reason we do this is because we will need access to that instance object from the “message” method.

Then, in the “message” method, we reference that instance object twice: when setting its “options.message” property and then when calling its “render” method. Both of those actions happen every time the “#/message/:text” route is requested.

Example # 2A

In Example # 2A, we can see the other problem with our code: we mix JavaScript in with our HTML. While this does work, but it is not the most efficient way to go, and we are mixing presentation with data. We will fix this by using Handlebars.js.

Example # 2B

In Example # 2B, we have replaced our “template” method with a call to the Handlebars.compile method. We pass it our string of HTML with one small but important change: the double-curly-braces templating syntax: {{message}}. A discussion of JavaScript templating is beyond the scope of this article, but it is important to note that by using Mustache.js (or a similar templating library), we do not need to mix-in JavaScript with the HTML string we pass to the Handlebars.compile method. The double-curly-braces templating syntax: {{message}} safely retrieves the data that we reference.

Example # 3

In Example # 3, we have the full code for our working example. Visually there is nothing going on in Example # 3 that you have not seen already in an earlier article. But if you look at the page source, you’ll see that there is a dramatic difference in how we go about instantiating the MessageView constructor, as well as how we reference the data in our view’s “template” method.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://examples.kevinchisholm.com/backbone/views/basics/html/part-ii.html

How to Demo:

This example will not appear to work any differently from the previous article’s examples. The important thing to note is what is going on under the hood. Take a look at the JavaScript file for Example # 3, so you can see that we have put the techniques discussed into action.

http://examples.kevinchisholm.com/backbone/views/basics/js/part-ii.js

Summary

In this article we learned two important optimization techniques for Backbone.js views: instantiating the view constructor only once, and separating the presentation from logic. We discussed the router’s “initialize” method as the best place to instantiate our view constructor, as well as how to use the JavaScript “this” keyword to make that instance object available to other methods in the Router class. We also learned how to leverage Mustache.js for client-side templating.

Getting Started with Backbone.js Views – Part I : Introduction

Backbone

Backbone.js LogoLearn how to separate presentation from logic by leveraging Backbone.js views2

One of the main principles of MVC is the separation of presentation, data and logic. While it may be tempting to mix these concerns in order to “get it out the door”, maintaining and extending this kind of code can quickly become a nightmare. In this article, we will be introduced to Backbone.js views, which provide a tremendous amount of abstraction that keeps presentation separate from logic.

In the previous articles about Backbone routes, we learned about extending Backbone classes. Specifically, we discussed extending the Backbone.Route class. When it comes to leveraging Backbone views, the approach is exactly the same. The only difference is that we will extend the Backbone.View class.

Example # 1A

In Example # 1A, we create a variable named MessageView. This variable will become a constructor function that inherits from the Backbone.View class. We accomplish this by using the extend method of the Backbone.View class. In very much the same way that we extended the Backbone.Route class, we pass an object to the Backbone.View.extend method. In this example, the object that we passed in has two properties: “template” and “render”.

The Template Property

The “template” property tells the view “what” to render. That is, it provides the actual HTML that will be injected into the DOM. This property must be a function. Since it is a property of an object, that makes it a method. Even though it ultimately provides a string of HTML, it must be a function. So we have made it a function that returns a string of HTML.

The Render Method

The “render” property is a function, which makes it a method. This method is where you provide the code that injects the template property’s HTML into the DOM. Let’s break down the code in this method:

this.$el – “this” refers to the object, which is the instance of the MessageView variable (which is a class that we created, and it extends, or inherits from the Backbone.View class). The Backbone.View class provides a property named: “$el”, which is a jQuery object that represents the view’s parent element.

this.$el.html – Since “$el” is a jQuery object, we can use its “html” method to inject markup into the DOM.

this.template – Refers to the “template” property that we discussed above (and don’t forget: that “template” property is a method).

Example # 1B

In Example # 1B, we have the the full JS code that is used in the working example URL (below). We are leveraging what we learned about Backbone.js routes but creating a route, and configuring it for a “default” route, and our “message” route. So, when the user chooses a “message” route (e.g. “#/message/hello” or “#/message/goodbye”), our “MessageView” class is instantiated.

But this example falls short in one pretty big way: our “message” route takes a parameter from the user, but we are not making any use of that in in the view. Let’s fix this.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 1:
http://examples.kevinchisholm.com/backbone/views/basics/html/part-i-ex1.html

How to Demo:

When the page loads, you will see the message: “This is the default route”. If you click either of the other two nav links, you will see the message: “Hello from the MessageView class!”. This markup is injected into the DOM by our MessageView class.

Example # 2

In Example # 2, we made two changes:

1) we use the “text” argument passed-into the “message” method that handles the “#/message:text” route. We get this information to the view in the following line:

view.options.message = text ? text : ‘No Message Provided!’;

Details: We use a ternary operator so that if there is no text parameter passed-in, we have a default message to provide to the view.

2) We inject the message into the view’s HTML in the following line:

‘The message is: ‘ + this.options.message + ‘

Details: In the HTML string that we are returning from the view’s “template” method, we reference the “message” property of the view’s “options” object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/backbone/views/basics/html/part-i-ex2.html

How to Demo:

When the page loads, you will see the message: “This is the default route”. If you click either of the other two nav links, you will see the message: “The message is: hello” or “The message is: goodbye”. This is because the “message” route passes the “text” parameter to the view as the “message” property of its “options” object.

Summary

In this article, we had a brief introduction to Backbone.js views. We learned how to extend the Backbone.View class, and create the HTML that will be injected into the DOM. We also learned how to pass parameters to the view so that it can be dynamic.

Getting Started with Backbone.js Routes – Part IV: Configuring an Initialization Function

Backbone

Backbone.js LogoLearn how to configure a function that initializes your Backbone.js router

In the last few articles of this series, we have learned the basics of setting up routes in Backbone.js. We’ve discussed setting up route handlers, specifying a default route, graceful actions for corner-cases, as well as passing parameters to routes. But what about setup tasks? Sometimes you may want to execute code in preparation for your routes, but these tasks need to be completed before the routes are activated.

In this article, we will learn how to set up an initialization function that will run once, and is guaranteed to do so before the router is started.

Like much of what we have already discussed with regards to Backbone, this functionality is fairly straightforward. In the object that we pass to the Backbone.Router.Extend method, we provide an “initialize” property, which will be a method.

NOTE: In the code examples that follow, I have removed most of the implementation code so that the example will be shorter and easier to follow.

Example # 1

In Example # 1, we have added a property that is passed-into the Backbone.Route.extend method. This property is named: “initialize” and it is a method. This method will execute before the router is started. In this example, we simply fade-in a message, letting the user know that the router is initialized.

HERE IS WORKING CODE LINK FOR EXAMPLE # 1:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iv-ex1.html

Example # 2

In Example # 2, we’ve upgraded our initialize method a bit. First, we moved all of the initialization code to the function: domSetup, just to keep the example code short and simple. There is no need to discuss the domSetup function in detail; it simply fades-in a message and sets up a few click handlers.

What interests us is the functionality that is provided here. Notice that when the page loads, if you click any of the nav links, nothing happens. This is because the router has not not been started yet. I have set a five-second timeout that delays the router’s start (the AJAX loader gif is spinning during this timeout). Once you see the green message fade-in, then all of the nav element clicks will work.

The point here was to demonstrate that if you have tasks you’d like to complete before the router is started, you can safely queue them up inside of the “initialize” method.

HERE IS WORKING CODE LINK FOR EXAMPLE # 2: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iv-ex2.html

How to Demo:

When the page loads, notice that there is an AJAX loader gif. As long as you see that AJAX loader, none of the nav element links work. Once the AJAX loader goes away and the message in a green box fades in, the nav links will work as expected. What is being demonstrated here is the fact that you can execute any setup code from the “initialize” method and then start the router manually as you wish. This is accomplished in the example code by placing all of the code that sets up the delay in the “initialize” method.

Summary

In this article, we learned how to set up an initialization function for a Backbone.js router. We learned about the “initialize” property of the object that we pass into Backbone.Router.extend, as well as how to manually start the router once our setup tasks have completed.

Getting Started with Backbone.js Routes – Part III: Passing Parameters to the Route

Backbone

Backbone.js LogoLearn how to pass values to your Backbone router in the URL

In the second part of this series: Getting Started with Backbone.js Routes – Part II: Handling Bad Requests, we learned how to handle route requests that are not configured in our router. This allows us complete control over the user experience, even when the request is one we had not anticipated. But what about parameters? How can we send the router a message? In other words, how can we pass a value in the URL that tells the application something specific?

In this article, we will learn how to pass parameters to the router, and in turn, how to access the values that are passed-in. So, for the examples that follow, we’ll imagine a very simple “order” page which allows you to specify the item you want to order in the URL. In order to keep the examples brief, I have removed any code that is not germane to the current discussion. But the full JS source code URL will be provided with each link to the working demo.

Example # 1

In Example # 1, we’ve set up a route named: “order/:item”. Up until now, our route names have been a single or hyphen-separated word. This new syntax, however, allows for more functionality.

Notice that in the route’s name, there is a colon. That colon tells Backbone that what follows is a parameter. So in this case, the actual route is “order/” and “:item” is a placeholder for whatever the user provides in that part of the URL. That value is an unknown, so we use the word “item” to represent this unknown value.

This route is handled by the method: “route”. Notice that the “route” method takes one argument: “item” (we could have named it anything, but I used “item” just to keep things consistent). This represents the parameter that was provided in the URL. So, inside of the “order” method, we now have access to that parameter.

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 1: http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex1.html

HERE IS THE LINK FOR EXAMPLE # 1’s JavaScript: http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex1.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair” or “#/order/shirt”. So, with each click, the message in the page will reflect the parameter passed in the URL after “#/order/”. You can enter whatever you like after “#/order/”, and that value will be reflected in the page’s message.

But what if the user wants to order more than one item?

Yes! This is a very logical feature to implement. It is common to specify a quantity when you order something. So, we’ll need to adjust our router so that the user can also provide the quantity in the URL in addition to the item name.

Example # 2

In Example # 2, we’ve added a new route: “order/:item/:count”. This route is also handled by the “order” method. There are two changes. This new route allows for a “count” parameter (i.e. “:count/”), and the “order” method takes a second argument: “count”.

Inside of the “order” method, we have updated the message that is injected into the DOM to include the “count” parameter, or the quantity of items to be ordered.

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 2:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex2.html

HERE IS THE LINK FOR EXAMPLE # 1’s JavaScript:

http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex2.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair/1” or “#/order/shirt/2”. With each click, the message in the page will reflect the parameter passed in the URL after “#/order/”, as well as the quantity (i.e. “#/order/quantity”).

But now we have a problem: If the user enters ““#/order/item” but does not specify a quantity, then the quantity will show up in the DOM as “undefined”. That’s not a good user experience, so let’s handle that exception.

Example # 3

In Example # 3, we’ve made two adjustments to our code. First, we’ve added a new route: “order/:item/”, which is handled by the “order” method. Second, we’ve added a quick check at the top of the “order” method: if (!count){count = 1}. This tells the “order” method: “hey, if the count argument is 0 or is not provided, then just make the quantity: 1).

HERE IS THE WORKING DEMO LINK FOR EXAMPLE # 3:

http://examples.kevinchisholm.com/backbone/routes/basics/html/part-iii-ex3.html

HERE IS THE LINK FOR EXAMPLE # 3’s JavaScript:

http://examples.kevinchisholm.com/backbone/routes/basics/js/part-iii-ex3.js

How to Demo:

Below the main nav is a brown navigation menu. As you click each menu item, notice that the URL changes. For example: “#/order/chair” or “#/order/shirt/”. Note that in the case of the first two links there is no quantity provided. In both cases, our “order” method sets the quantity to: 1.

Summary

In this article we learned how to pass parameters to a Backbone.js route. We learned the syntax needed to specify which part of the route request is the actual route and which part is the parameter. We discussed how to access that parameter in the function that handles the route request, how to allow for multiple parameters, and how to handle corner cases where an expected parameter is not provided.