The JavaScript “this” Keyword Deep Dive: Constructor Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword differs when instantiating a constructor (as opposed to executing the function).

In earlier articles of the “The JavaScript “this” Keyword Deep Dive” series, we discussed how the meaning of “this” differs in various scenarios. In this article, we will focus on JavaScript constructors. It is critical to keep in mind that in JavaScript, constructor functions act like classes. They allow you to define an object that could exist. The constructor itself is not yet an object. When we instantiate that constructor, the return value of the instantiation will be an object, and in that object, “this” refers to the instance object itself.

So, inside of a constructor function, the JavaScript keyword refers to the object that will be created when that constructor is instantiated.

Example # 1

In Example #1, you’ll see that we have created two new properties of the window object: “music” and “getMusic”. The “window.getMusic” method returns the value of window.music, but it does so by referencing: “this.music”. Since the “window.getMusic” method is executed in the global context, the JavaScript “this” keyword refers to the window object, which is why window.getMusic returns “classical”.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor.

We’ve also created a constructor function named “Foo”. When we instantiate Foo, we assign that instantiation to the variable: “bar”. In other words, the variable “bar” becomes an instance of “Foo”. This is a very important point.

When you instantiate a JavaScript constructor function, the JavaScript “this” keyword refers to the instance of the constructor. If you remember from previous articles, constructor functions act like classes, allowing you to define a “blueprint” object, and then create “instances” of that “class”. The “instances” are JavaScript objects, but they differ from object literals in a few ways.

For an in-depth discussion of the difference between an object literal and an instance object, see the article: “What is the difference between an Object Literal and an Instance Object in JavaScript? | Kevin Chisholm – Blog”.

Earlier on, we established that inside a function that is not a method, the JavaScript “this” keyword refers to the window object. If you truly want to understand constructor functions, it is important to remember how the JavaScript “this” keyword differs inside that constructor. When you look at the code, it seems as if “this” will refer to the window object. If we were to simply execute Foo as if it were a normal function, this would be true (and we will discuss this scenario in Example # 3). But we don’t simply execute Foo; we instantiate it: var bar = new Foo().

When you instantiate a JavaScript constructor function, an object is returned. The JavaScript “this” keyword has a special meaning inside of that object: it refers to itself. In other words, when you create your constructor function, you can use the “this” keyword to reference the object that WILL be created when the constructor is instantiated.

So, in Example # 1, the getMusic method returns “this.music”. Since the “music” property of Foo is: “jazz”, then the getMethod returns “jazz”. When we instantiate Foo, the variable “bar” becomes an instance of Foo, so bar.getMusic() returns “jazz”.

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

Example # 2

In Example # 2, we have changed Foo’s “GetMusic” method. Instead of returning “this.music”, it returns an executed function. While at first glance, it may seem as though the “getMusic” method will return “jazz”, the JSFiddle.net link demonstrates that this is not the case.

Inside of the “getMusic” method, we have defined a variable that is equal to an anonymous function: “myFunction”. Here is where things get a bit tricky: “myFunction” is not a method. So, inside that function, the JavaScript “this” keyword refers to the window object. As a result, that function returns “classical” because inside of “myFunction”, this.music is the same thing as window.music, and window.music is “classical”.

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

Example # 3

In Example # 3, we have an example of a scenario that you don’t want: executing a JavaScript constructor function instead of instantiating it. Hopefully, this is a mistake that you will catch quickly, but it can happen. It is also possible that you might inherit code that contains such a bug. Either way, this is bad.

While the Foo constructor still has a “getMusic” method, because we execute Foo, instead of instantiating it, the code inside of Foo overwrites two properties that we created earlier: window.music and window.getMusic. As a result, when we output the value of “this.getMusic()”, we get “jazz”, because when we executed Foo, we overwrote window.music, changing it from “classical” to “jazz”.

While this is a pattern that you want to be sure to avoid in your code, it is important that you be able to spot it. This kind of bug can leave you pulling your hair out for hours.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/2RFa3/2/

Summary

In this article we learned how the JavaScript “this” keyword behaves in a constructor function. We learned about instantiating a constructor and the relationship between “this” and the instance object. We also discussed a couple of scenarios that are important to understand with regards to “this” and constructor functions.

The JavaScript “this” Keyword Deep Dive: Nested Methods

JavaScript

JavaScript LogoDepending on the scenario, the JavaScript “this” keyword may refer to the object of which the method is a property, or the window object.

In an earlier article: The JavaScript “this” Keyword Deep Dive: Nested Functions, we learned how functions that are not methods evaluate “this” to the window object. In that post, we demonstrated that no matter how deeply you nest functions, this behavior is always the same. In this article, we will learn how the JavaScript “this” keyword behaves in nested methods.

So, here, it might be a good idea to quickly answer the question: “What is a nested-method”?

A method is a function that is a property of an object. A nested method occurs when a method, in turn, returns an executed method.

The reason that this scenario is an important one to consider is that while you may execute method A, if that method returns the executed method of object B, then inside of that second method, the JavaScript “this” keyword refers to object B (not object A).

Example # 1

In Example # 1, we have added a property to the window object named “music”, and set the value to: “classical”. We have also added a method to the window object named “getMusic”, which returns the value of window.music. But, notice that instead of referencing window.music, the method returns: this.music. The reason that works is that since the method is a property of the window object, “this” refers to the window object. This means that this.music is the same thing as this.music, and the value of that property is: “classical”.

We have also created an object named “foo”, and it has the exact same-named properties we specified above, and the “getMusic” method has the exact same code: return this.music. But foo’s “getMusic” method returns “jazz”, because foo.music = “jazz”, which means that inside of foo’s “getMusic” method, the JavaScript “this” keyword refers to the foo object, and foo.music is “jazz”.

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

Example # 2

In Example # 2, we have created an object named: “foo”, which has a method named: “getMusic”. The getMusic method returns an object with two properties: “music”, which is equal to “rock”, and “getMusic” which returns this object’s “music” property.

When we pass the output of foo.getMusic() to the console, we see that is: “rock”, and now “Jazz”. The reason for this is that foo’s getMusic method ignores foo’s music property. That is, it returns an object, and that object’s getMusic method returns its own “music” property. In this scenario, we have nested a method: foo.getMusic, that returns the executed method of another object. The reason for this example is to demonstrate the fact that even though foo.getMusic returns a nested method, when the nested method utilizes the JavaScript “this” keyword, it refers to the object that it is a property of, not foo.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/5uUJ8/1/

Example # 3

So, in Example # 3, we take the exact same approach as Example # 2, providing an additional level of method-nesting. As you might expect, the innermost method returns “metal”, the value of the “music” property to which the getMusic method belongs.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/5uUJ8/2/

Example # 4

Example # 4 is somewhat similar to Example # 3, except that the nesting is logical, not physical: each getMusic method, in turn, calls the getMusic method of a different object. The end result is the same as Example # 3: “metal”. But instead of one method returning an anonymous object whose getMusic method is executed, each of the getMusic method calls here return the execution of another named-object’s “getMusic” method.

It is also important to note that the first console.log call: this.getMusic returns “classical”, because the window.getMusic method is a property of the window object. But, each of the other objects (i.e. “rockObject” and “metalObject”) have its own “music” properties, so when the “metalObject.getMusic” is called, it returns the value of metalObject’s “music” property, which is “metal”.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 4: http://jsfiddle.net/5uUJ8/3/

Summary

In this article we discussed how the JavaScript “this” keyword behaves inside of nested methods. We learned what a nested method is. And we also learned how, in this scenario, the JavaScript “this” keyword refers to the object of which the method is a property, not the window object.

The JavaScript “this” Keyword Deep Dive: Nested Functions

JavaScript

JavaScript LogoLearn how the JavaScript “this” keyword behaves inside of function declarations and expressions, even when nested 10 levels deep.

In the article: The JavaScript “this” Keyword Deep Dive: An Overview, we discussed a number of scenarios in which the JavaScript “this” Keyword has different meanings. In this article, we will concentrate on functions and methods.

It’s important to note that methods are functions. What makes a method a method is that the consumer of the code specifies an object, and then calls a method of that object.

Example # 1

In Example # 1, we have executed a function and a method. We have actually executed two functions, but the second function: “someMethod” is actually a method of the “bar” object. We know this because we have used the syntax: object.method().

It’s important to understand the difference between executing a function and a method.

Example # 2

foo = function (){ return this.music; }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/

In Example # 2, we have executed the function “foo”, which returns the value of “this.music”: “classical”. Both console.log statements return the value: “classical”, because since we are not inside of a method, the JavaScript “this” keyword refers to the window object, and at the top of the code, you’ll see that window.music is equal to “classical”.

Example # 3

foo = function (){ function bar(){ function baz(){ function bif(){ return this.music; } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 2: http://jsfiddle.net/84Yd4/1/

In Example # 3, things get a bit silly, but the effect is the same. Even inside of nested functions, because none of these functions are methods, the JavaScript “this” keyword refers to the window object. And “this.music” is the same as “window.music”, which is equal to “classical”.

Example # 4

foo = function (){ function bar(){ function baz(){ function bif(){ function billy(){ function bobby(){ function betty(){ function jetty(){ function jimmy(){ function judy(){ return this.music; } return judy(); } return jimmy(); } return jetty(); } return betty(); } return bobby(); } return billy(); } return bif(); } return baz(); } return bar(); }; console.log(this.music); //’classical’ (global) console.log(foo()); //’classical’ (global)

In Example # 4, the function-nesting concept is taken to a ridiculous level. Nonetheless, the output is exactly the same: “this.music” is the same as “window.music”, which is equal to “classical”. It does not matter how deeply a function is nested. Unless it is a method of an object, the JavaScript “this” keyword will always refer to the window object.

HERE IS THE JS-FIDDLE.NET LINK FOR EXAMPLE # 3: http://jsfiddle.net/84Yd4/2/

Summary

In this article we learned that when a function is not specified as a method of an object, the JavaScript “this” keyword refers to the window object. This is true even in the case of nested functions. In fact, no matter how many levels deep we nest functions, the JavaScript “this” keyword refers to the window object.

The JavaScript “this” Keyword Deep Dive: An Overview

JavaScript

JavaScript LogoLearn the subtle yet critical details that allow you to leverage the JavaScript “this” keyword.

In JavaScript, the “this” keyword is one of the most overly-used yet under-utilized aspects of the language. It is also one of the most mis-understood topics. While it facilitates more readable, expressive object-oriented JavaScript, improper use is a catalyst for confusing code that is difficult to debug.

Personally, I’ve struggled to understand the mystery. I’ve heard many unusually long-winded explanations, which I feel only contribute to the silliness. Simply put: In JavaScript, “this” refers to the object upon which a function is invoked. That’s it.

In JavaScript, “this” refers to the object upon which a function is invoked.

This means that “this” can only be used in a function, or globally. When used in either of these cases, “this” refers to the window object. When the function is a method of an object, then “this” refers to the object that the method is a member of. When the function is a constructor, then “this” refers to the instance object. There is much more to talk about with regards to what “this” means in varying scenarios, but these are the most common situations.

Example # 1

In Example # 1, we have added a property to the window object, named it: “music”, and assigned the value “classical”. In the line that follows, we output the value of “this.music”, and the result is: “classical”.

The reason for the output is simple: If you execute arbitrary code in the global context (i.e. outside of a function), then “this” refers to the window object. Executing arbitrary code in the global context is highly discouraged, but it is important to understand this behavior from a theoretical standpoint; in the global context: “this” will evaluate to the window object.

Example # 2

In Example # 2, we have added a function named foo, and then logged the output of that function’s execution. The resulting value is: “classical”. Some may have expected the output to be “blues”. This is a common mistake.

In the function “foo”, “music” is a variable. The “this” keyword has to do with objects, never variables (there is a very subtle scenario where “this” refers to a variable, which we will address in a later post). So the fact that there is a variable named “music” is completely meaningless in this example. The function “foo” does only one thing: it returns the value of this.music. In that function, “this” is the widow object, and the value of window.music is: “classical”. So, the variable “music” is completely ignored.

Example # 3

In Example # 3, we have added an object named “bar”. This object has two properties: “music”, which has a value of “jazz” and “getMusic”: a method that returns the value of bar’s “music” property.

The “getMusic” method has a line of code that you have seen in previous examples: “return this.music”. But why does that line of code return: “jazz”? The reason for this behavior is that when a function is a method of an object, the “this” keyword refers to the object upon which that function is invoked. In this case, the object is “bar”, and bar’s “music” property is equal to “jazz”, so “this.music” is equal to “jazz”.

Example # 4

In Example # 4, we have added the constructor function: “Baz”. “Baz” has a property named “music”, and it is equal to “rock”. It also has a property named “getMusic”, which is a method. The “getMusic” method returns the value of Baz’s “music” property.

You may be thinking that inside of the “Baz” constructor, the “this” keyword refers to the window object, as discussed in Example # 2. If we were to simply execute “Baz” (e.g. Baz() ), then yes, the property window.music would be overwritten and given the value of “rock”, and there would be a new global property named “getMusic”, which would return “rock”.

But that’s not what happens. After we create the constructor: “Baz”, we instantiate it, which results in a variable named “bif”, an instance of “Baz”. When you instantiate a JavaScript constructor function, the “this” keyword inside of that function refers to the instance object that the constructor returns.

HERE IS THE JS-FIDDLE.NET LINK

FOR EXAMPLE # 3:

Summary

In this article we discussed the high-level details of the JavaScript “this” keyword. We learned that it refers to the object upon which a function is invoked, and how it means different things in different scenarios. The scenarios we covered are: the window object, inside of a function, inside of a method, and inside of a constructor function.

Book Review: Node for Front-End Developers, by Garann Means

Node.js

Node for Front-End Developers, by Garann Means - CoverIf you are just getting started with server-side JavaScript, “Node for Front-End Developers” offers a fast, high-quality introduction.

The ubiquity of front-end JavaScript is undeniable. Not only has the appetite for web-based content increased dramatically, but so has the appetite for sophisticated user interfaces. More and more, visitors expect web-based content to offer complex interaction and high-performance. The explosion of mobile device use has only exacerbated this dynamic. Ryan Dahl’s Node.js turned the whole concept of JavaScript on its head by providing an open-source tool that allows the language to be leveraged on the server-side, significantly expanding the potential of this language.

Node for Front-End Developers, by Garann Means is a fast introduction to this incredibly powerful technology. The concept of creating a web-server provides a door through which clear and concise explanations present the basic concepts of server-side JavaScript. I found it particularly helpful that for such a short book, topics such as the query string, post data, path data routing, asynchronous events, templating, databases and MVC are well handled.

The book’s length is deceptive; readers will find a wealth of useful information here. While each topic represents a thread that deserves further reading, anyone who is new to Node.js will find Ms. Means’ introduction helpful. Her writing style is both relaxed and professional. From using NPM to install modules, to real-time communication with WebSockets, Node for Front-End Developers offers a range that is just enough to excite the reader, yet never too much detail. Any of the examples can be typed into your favorite text editor and fired-up with minimal effort. This is critical when delving into a new topic, and makes your introduction to Node.js disarming and fun.

  • Title: Node for Front-End Developers
  • Author: Garann Means
  • Publisher: O’Reilly Media
  • Date Published: February 7, 2012
  • Language: English
  • ISBN-10: 1449318835
  • ISBN-13: 978-1449318833

Book Review: High Performance JavaScript by Nicholas C. Zakas

JavaScript

High Performance JavaScript by Nicholas C. Zakas Book Cover
High Performance JavaScript by Nicholas C. Zakas
While JavaScript engines are getting faster every day, complex logic or heavy DOM manipulation can still lead to sluggish browser performance. Nicholas C. Zakas takes you on a journey into the more subtle areas of JavaScript, providing a deeper understanding of how to create faster and more responsive user interfaces

For many front-end web developers, mastering concepts such as context, closures or callbacks is a major milestone in learning JavaScript. As you start to work with asynchronous events and complicated DOM manipulation, writing JavaScript code can become even more adventurous and quite rewarding. But it is right about this time that you may start to notice sluggish or even non-responsive pages. High Performance JavaScript (Build Faster Web Applications Interfaces), by Nicholas C. Zakas, provides numerous insights that will help you to understand why some of these issues arise and how to prevent them from happening.

With the help of Ross Harmes, Julien Lecomte, Steven Levithan, Stoyan Stefanov, and Matt Sweeney, Mr. Zakas leads the reader through a series of articles that detail advanced techniques for better JavaScript performance. In many cases, it comes down to programming patterns that are not unique to JavaScript, but lend themselves well to this context. But there is also JavaScript-specific advice with regard to cloning nodes, caching references to objects and optimizing expensive operations. Inside these 202 pages is expert advice on how to refactor loops, conditionals and recursion, as well as smarter regular expressions and AJAX. You’ll also find great coverage of the best tools available for improving JavaScript performance.

If you are an intermediate to advanced front-end web developer who is looking to gain a deeper understanding of the JavaScript language, this book is an invaluable resource.

  • Book Review: High Performance JavaScript by Nicholas C. Zakas
  • Length: 202 pages
  • Publisher: O’Reilly Media; 1st edition (March 30, 2010)
  • Language: English
  • ISBN-10: 059680279X
  • ASIN: B00CVDSYLG

Who Are the Top JavaScript Developers I Should Know About?

JavaScript

JavaScript LogoThere are a few developers who are particularly knowledgeable about JavaScript. In many cases, their work and their writings are real gems that can provide a deeper perspective on the language.

In this article, I have created a summary of the top JavaScript Developers I’ve come across in the last few years. In each case, I’ve provided a link to the site that I feel best represents their offerings to the JavaScript community. There are likely other links that are applicable for that developer, this is a brief summary.


Brendan Eich

Brendan Eich’s Blog

Although Brendan Eich current efforts are spent as chief technology officer at the Mozilla Corporation, he is the creator of the JavaScript language. If you are the least bit interested in JavaScript, he is in my opinion, someone you’d want to know about.


John Resig

ejohn.org

This is a no-brainer. While not the most actively maintained blog, it is rich with advanced JavaScript information. As the creator of the jQuery JavaScript library, he is someone that every JavaScript developer should pay attention to.


Nicholas C. Zakas

NCZOnline

Nicholas C. Zakas has authored of three of my favorite JavaScript books: Professional JavaScript for Web Developers, High Performance JavaScript (Build Faster Web Application Interfaces) and Maintainable JavaScript. He is an excellent writer and posesses a very advanced knowledge of the language.


Stoyan Stefanov

phpied.com

JavaScript Patterns is one of my favorite JS books. I’ve read it front to back at least four or five times and there is always something new to be learned from it. Currently a software engineer at Facebook, Stoyan is also author of Web Performance Daybook vol 2, JavaScript for PHP Developers, and Object-Oriented JavaScript, Stoyan Stefanov is one of the most prolific JavaScript developers I am aware of. He offers a very advanced perspective on JavaScript that while not always easy reading, is worth the effort. I’ve learned a great deal about JS from reading his books.


Addy Osmani

AddyOsmani.com

Currently working on the Chrome team at Google, Addy Osmani is the author of the book: Developing Backbone.js Applications
Building Better JavaScript Applications, as well as Learning JavaScript Design Patterns. He is a highly respected JavaScript developer whos insights and contributions to the community are invaluable.


Douglas Crockford

javascript.crockford.com

Douglas Crockford is the author of JavaScript: The Good Parts, and the creator of JSON (JavaScript Object Notation). He is someone that clearly thinks and cares about JavaScript a great deal, and has a very deep perspective.


David Walsh

davidwalsh.name

A Web Developer at Mozilla, David is one busy guy. He is a contributor for SitePen, writes great technical articles about Dojo and lectures at some excellent technology conferences.


Kyle Simpson

getify.me

Kyle is the author of You Don’t Know JS JavaScript book series. While his website is pretty bare-bones, it offers a ton of links to his projects and teachings. Kyle has an incredibly deep knowledge of JavaScript and is an excellent speaker / instructor.


Dustin Diaz

github.com/ded

Co-author of JavaScript Design Patterns (an excellent book), Dustin Diaz is a big contributor to the JavaScript community.


Ben Alman

benalman.com

Ben is the creator of some well known jQuery plugins such as: jquery-bbq, jquery-throttle-debounce, and jquery-resize. If I had a dollar for every time I’ve come across some of his JS code pasted into a script, I’d be rich.


Remy Sharp.

remysharp.com

Remy based in the UK, and is one of the curators of HTML5Doctor.com. I have often enjoyed his writings and find him to me one of the more passionate and talented JavaScript developers out there.


Azat Mardanov

azat.co

This is a suggestion from friend and UX Specialist Ken Whaler of Gyroscope Studios in Portland, OR. I’m not familliar with Azat, but after a quick glance, I felt this site is definitely a treasure-trove of solid JavaScript information.

Easy JavaScript Object Context Switching with jQuery.proxy()

jQuery

JavaScript LogoA popular saying in the Real Estate business is: “Location, location, location!” Well, in JavaScript, it’s all about “context”. When you want to leverage the very powerful keyword: “this”, then understanding the current context is critical.

So, those experienced with native JavaScript should be comfortable with the concept of context (If you are not, take a moment to brush up on this subject; it’s important.) When you need to specify context, you would normally use the .call() or .apply() methods. The jQuery folks have also provided a way to accomplish this with their .proxy() method. This method takes two arguments, which are: the function to be executed and the object whose context should be targeted. Any additional arguments are optional and are passed to the function that is executed.

Example # 1

In Example # 1, we have created two simple objects: “foo” and “bar”. Note that each object has one property named “music”. Next, we set up two click event handlers. In each case, we execute the “handler” function. And that function makes reference to “this”. If we were to run that function by itself, the output of the alert would be “undefined”, because when doing that, “this” refers to the window object, which at this time has no property named “music”.

So, by using the jQuery.proxy() method, we specify the context within which the “handler” function should be executed.

Here is the JS Fiddle link for Example # 1: http://jsfiddle.net/Shm47/

Example # 2

In Example # 2, we have taken our cause to the DOM. We first create a function named toggleColor, which when passed a class name, will toggle that class name.

Next, we set up two click event handlers. In each case, we leverage jQuery.proxy(), to call the “toggleColor” function, and specify the context within which it should run. We’re also specifying the class name to be passed to that function.

Here is the JS Fiddle link for Example # 2: http://jsfiddle.net/WzDUj/

Summary

In this article, we learned about the jQuery.proxy() method. In doing so, we discussed how it is used to specify the context within which a function should be executed. First we demonstrated how you can leverage this function using object literals. We then showed how you can do so by using DOM elements.

Helpful Links for the jQuery.proxy() method

http://api.jquery.com/jQuery.proxy/
http://stackoverflow.com/questions/3349380/jquery-proxy-usage
http://stackoverflow.com/questions/4986329/understanding-proxy-in-jquery
http://blog.kevinchisholm.com/javascript/context-http://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/object-literals/
http://blog.kevinchisholm.com/javascript/difference-between-scope-and-context/

JavaScript Concatenation and Minification with the Grunt.js Task Runer

Node.js

Grunt.js LogoCombine multiple JS files into one using JavaScript, Node.js and Grunt.

In the article: “Getting Started with Grunt: The JavaScript Task Runner,” we covered the bare-bones basics of how to set up and use Grunt, to automate and manage your JavaScript build task. In that article, we used a Grunt plugin called “grunt-contrib-uglify” to minify and obfuscate our JS code. But while minification is a common task for any build system, file concatenation is also a technique used to minimize the number of http requests. This helps to improve web page performance. In this article, we will look at the Grunt plugin: grunt-contrib-concat. It exposes a number of very useful methods for simple, to advanced file concatenation.

Example # 1

In Example # 1, we have the contents of “package.json“. Naturally, Grunt is listed as a dependency, but there is a reference to the “grunt-contrib-concat” plugin as well.

The Project File Structure – And Files to be Concatenated

 

The Empty Distribution Folder
The Empty Distribution Folder

 

 

Example # 2

In Example # 2, we have the JavaScript code that will set up and run the Grunt tasks. There are two sections to this code: the call to the grunt.initConfig() method, and the two commands that load the plugin and register the task.

Grunt Init configuration

The method: initConfig belongs to the grunt object. For this article, we are concatenating three JavaScript files. As you can see, the sole property to the object-literal passed to the initConfig method is concat. Its value is another object with two properties: “options” and “dist“. The “dist” property provides an object with critical details for this operation: the location of the source files (“src“). It also provides the location of the file to be created that contains all of the source files (“dist“). Note that the value of the “src” property is an array. This ensures that any number of files can be specified. The path is relative to the Gruntfile. In this example, the “options” property specifies the string that will be used to separate each concatenated file.

Loading the Grunt Plugin and Registering the task

Under the call to the grunt.initConfig() method, we load the “grunt-contrib-concat” plugin by passing it as a string to the grunt.loadNpmTasks method. This makes the plugin available to the rest of our code. Next, we register the “default” task with a call to the grunt.registerTask() method. The first argument is the name of the task (in this case it is “default“). The second argument is an array containing one or more named tasks.

That is all we need to run our tasks. So now, in the terminal, we simply type: “grunt“. After grunt has completed running, you should see a new file in the “dist” folder named: “allScripts.js.

The Built File
The Built File

Summary

In this article, we talked about JavaScript minification using Grunt. We discussed configuring the project dependencies in the file: package.json, which is needed in order for our application to work properly. We also reviewed the file: Gruntfile.js, which is where we did set configuration properties for the build, and then run the tasks. There is plenty to dive into on the subject of minification with Grunt. This article provided the most basic elements of how to set, configure and run a task that combines multiple JavaScript files into one.

Helpful Links for: Grunt.js file concatenation

http://stackoverflow.com/questions/16377674/using-grunt-to-concatenate-all-vendor-javascript-files

https://github.com/gruntjs/grunt-contrib-concat

http://stackoverflow.com/questions/12722855/using-grunt-concat-how-would-i-automate-the-concatenation-of-the-same-file-to-m

Getting Started with Grunt: The JavaScript Task Runner

Node.js

Grunt.js LogoAutomate and manage your JavaScript build tasks with JavaScript, Node.js and Grunt.

Today, even the most straightforward web-based application will involve JavaScript, and chances are that JS code will not be too simple. In-fact, it is often inevitable that your JavaScript could start to grow over time and / or span multiple files. When these dynamics are in-play you’ll find yourself spending more and more time having to organize and test your code. Regardless of the details, this kind of maintenance quickly becomes tedious. I think many will agree that when humans have to perform repetitive / tedious tasks, the chance of error increases. Fortunately, this is the exact kind of work that a computer is thrilled to do, and do well. Using a built tool to manage your JavaScript build tasks is not only efficient, but also a smart way to go.

Grunt is promoted as a “Task Runner.” Semantics aside, it is an aptly named tool that provides a significant level of flexibility and power, when it comes to managing and automating your build tasks.

In this article, I will intentionally “scratch the surface.” While there is a great deal of depth to Grunt, getting started is a critical first step. My focus here is to provide you with information that simply enables you to set the minimum configuration required for your first (albeit simple) automated task with Grunt.

Prerequisites

In order to use Grunt, you’ll need Node.js and the The Grunt CLI (Command-Line Interface). Installing Node is beyond the scope of this article. If you have not installed Node yet, you can start here: http://nodejs.org/

The Grunt Command-Line Interface

The Grunt CLI is used to launch Grunt. While this may sound a bit confusing, installing the Grunt CLI does not actually install the Grunt task runner. The CLI is used to launch whatever version of Grunt is defined in your package.json file (more on that file later). The advantage of this is that your projects can all use different versions of Grunt without concern for conflicts. The CLI does not care, it simply launches whatever version your project uses.

(You might need to use the sudo command when executing npm install, depending on your account priviliges.)

Note that in the example above the “-g” flag is used. This is recommended. It installs the module globally so that it can be executed from any folder on your machine, and need not ever be installed again.

package.json

Once you have installed the grunt-cli globally, you can put your project together. The first step is to create a package.json file. The package.json file is a feature of node.js. You can learn more about it here: https://npmjs.org/doc/json.html

In this example, we have named this project: “Grunt-Test-1”, and given it a version #. Both of these values are arbitrary, and completely up to you. But keep in mind that the “name” property is potentially used by Grunt in some cases, so choose a name that makes sense. The “devDependencies” property is an object that whos whose keys contain node modules that your project depends on. The value for each key is the exact (or minimum) version number required for that module.

The Project File Structure

Image # 1: The project’s file structure

Once your package.json file is ready, simply run the following command: “npm install”. Node will refer to your package.json file in order to understand what it needs to install so that your project works correctly. Keep in mind that the “installation” is simply a download that is local to this folder. Its is not “installed” on your computer, like a native / compiled application.

Example # 1

For this example, we have only two dependencies: grunt, and grunt-contrib-uglify. The “grunt” requirement is critical because we want to use Grunt. Everything else is optional. But if grunt is the only dependency, then there won’t be too much we can do. Grunt plugins allow us to define tasks that can be managed by Grunt. The “grunt-contrib-uglify” plugin provides JavaScript minification and obfuscation. For this article, we will simply minify a JavaScript file and save it with a new name.

Once you have created your package.json file, you can install all required modules with two easy words: “npm install”. Entering that command in your terminal will allow you to leverage the Node Package Manager, otherwise known as: “npm” (make sure you are in the root folder of your project). The Node Package Manager will look for a file named package.json in the current folder, and read the devDependencies object. For each property of the “devDependencies” object, npm will download whatever file is specified by the version # you have provided as a value for that property.

One of the ways in which this approach is so helpful is that it negates the need to commit large files to your version control. Node modules are often a combination of text files (e.g. “.js”, “package.json”, “README”, “Rakefile”, etc.) and executables. Sometimes a combination of just a few dependencies can add several megabytes to your project, if not more. Adding this kind of weight to your code repository not only eats up disk space, but it is somewhat unintuitive because version control systems are really meant to store and manage text files that you (or your teammates) will change over time. Node.js modules are managed by the contributors of those modules, and you probably won’t need (or want) to change their source code. So, as long as your project contains the package.json file, whenever you (or anyone on your team) check out that repo, you can run “npm install” to the exact versions of the modules you need.

The Gruntfile

The Gruntfile is the JavaScript code you create to leverage the power of Grunt. Grunt always looks for a file named: “Gruntfile.js” in the root of your project. If this file does not exist, then all bets are off.

Inside of Gruntfile.js, all of your code will be wrapped in one function: module.exports.

Example # 2

In Example # 2, we have defined the “exports” method of the “module” object. Right now it does nothing, but all of your grunt code will go inside of this function.

Example # 3

In Example # 3, we make a call to the grunt.initConfig method. This method takes an object as its sole argument. In this object, we set properties that provide the details Grunt needs in order to work the way we want. Here we set one property: “pkg”. In order to set the value for that property, we tell grunt to read the contents of our “package.json” file. The main reason for this is that we can use the metadata that is stored in package.json, and use it in our tasks. The two delimiters: <% %> can be used to reference any configuration properties. For example: <%= pkg.name %> would display the name that you have given your project. In this case it is: “Grunt-Test-1”, but we could also access the version number of our project in this manner: <%= pkg.version %>.

Since we will be using the “grunt-contrib-uglify” plugin, lets update Gruntfile.js so that it is configured to leverage this plugin.

The Empty Build Folder
The Empty Build Folder

Image # 2: The empty build folder

Example # 4:

In Example # 4, we have added a new property to the config object: “uglify”, which provides the detail that the “grunt-contrib-uglify” plugin needs. This property is an object which, in-turn, has two properties that are objects. As the name suggests, the “options” property contains options for the “grunt-contrib-uglify” plugin. The “build” property is an object that provides two properties that are critical to the “grunt-contrib-uglify” plugin:

  • src: The location of the file to “uglify”
  • dest: The location where the “uglified” file will be placed

While we have provided some important details, running Grunt at this point will produce no results because there are no tasks specified. Let’s take care of that next:

Example # 5:

In Example # 5, we have made two changes: We load the “grunt-contrib-uglify” plugin, and then we register the default task, which in this case is: “uglify”. Notice that the “uglify” task is passed to the registerTask() method, as the sole element of an array. This array can contain as many tasks as you like, always represented as a string. The purpose of the “default” task is to let Grunt know that outside of any other named tasks that are registered, this is the list of tasks that should be executed.

Now that we have provided the minimum details needed, we can run Grunt by simply typing “grunt” in the terminal. Once Grunt completes, you should see a new file in the “build” folder that is in the root of your project. That file should be named as per the details provided in the “uglify” section of the object passed to the grunt.initConfig() method. You’ll see that file has been “uglified,” meaning that it has been minified and obfuscated. The end result should be a significant reduction in file size.

The Built File
The Built File

Image # 3: The  built file

Summary

The example used in this article was very basic (about as basic as you can get!). My goal was to provide the critical base information needed in order to understand, setup and use Grunt for the first time. There is a great deal of power available from Grunt. While it may not fit everyone’s needs, it can, in many cases, provide a robust and actively maintained open-source framework with which to create simple or complex build processes.

Helpful Links for Getting Started with Grunt

http://gruntjs.com/

http://gruntjs.com/getting-started

http://net.tutsplus.com/tutorials/javascript-ajax/meeting-grunt-the-build-tool-for-javascript/

http://blog.mattbailey.co/post/45519082789/a-beginners-guide-to-grunt

Creating a Simple JSONP API with Node.js and MongoDB

Node.js

MongoDB LogoBy leveraging the Node.js middleware “express”, we can create functionality for viewing, adding or deleting JSON data.

In a previous article: “Using Mongoose ODM to Connect to MongoDB In Your Node.js Application,” we learned the basics about connecting to a MongoDB database in a Node.js application. Because that article barely skimmed the surface of what is possible, we’ll take a few more baby steps here with our data. And for the sake of brevity, I’ll skim over the Mongoose.js details. If needed, you can refer to the article mentioned above for more details on that.

The goals for this article are:

  • Allow the user to view all data in the database
  • Allow the user to make a JSONP call to get all data
  • Allow the user to add a new name to the Sales database
  • Allow the user to delete all data in the database

When completed, this will be far from a robust or production-ready application, but we will, at minimum, learn how to view / add / delete data in our MongoDB database, using clean URLs in the browser.

Dependencies

In order to use the code in this article, you’ll need the following installed on your computer:

Node.js
MongoDB

Installation of these components is beyond the scope of this article, but if you follow the provided links, you will be pointed in the right direction.

File Structure

  • app.js
  • package.json

For this article, we will need two files: app.js and package.json. So, in your project folder, create these two empty files. The following sections will explain what to put in them.

Example # 1A

In Example # 1A, we have the contents of package.json. Note that for a more detailed discussion about package.json files you can search this blog for helpful articles. The two dependencies declared are “mongoose” and “express”. When you use node package manager to install dependencies, npm will download and install mongoose and express for us.

Example # 1B

In Example # 1B we see the command needed to install the dependencies for our application. Once you run this command, you will have everything needed to start writing code.

Getting Started

Open app.js in your text editor. From this point on, you can copy / paste the code in each example into the app.js (or you can scroll to the bottom of this page and paste the entire code listing in one step).

Example #2

In Example #2, we declare all of the top-level variables we’ll need in our script. Take note of “app”, which will be used to leverage the express middleware that we listed as a dependency. Also, “initApp”, which is called from the very end of this script. It is used to start the HTTP server.

Example #3

In Example #3, we have our database implementation. The details are identical to those in the previously mentioned article, so we’ll skip over that.

Example #4

In Example #4, we get into something new. If you remember from Example #2, the variable: “app” is an instance of the Express middleware object. We use the .get() method of that object to define what will happen when certain requests are made. When users navigate to the root of our web application, they are presented with a simple message. We accomplish this by passing two arguments to the .get() method: a string representing the requests we want to respond to (i.e. “/”), and an anonymous function. That anonymous function takes two arguments: “req” and “res”, which represent the request that was made, and the response object that we will send back. We use the .end() method of the response object, and pass in the string we want to send to the browser.

The second call to the app.get() method responds to “/json/delete”. It, in turn, calls a function named: utils.deleteAllData(), which will be explained a bit later.

Example #5

In Example #5, we use the app.get() method to respond to the request: “/json”. For this request, we want to show all of the data in the database. We start off by requesting all of the data in the database: salesMember.find({}).exec(). The anonymous function that is passed to the exec() method provides access to an error object (if there is one), and the results of our search. In this case, the result object is JSON, which contains all the data in the database, which we then stringify.

We then use the utils.isJsonCallback() method to determine if the user added a callback function name to the query string. If so, we wrap our database JSON with the named callback. We then deliver the JSON by passing it to the res.end() method.

Example #6

In Example #6, we respond to a request to add a new user to the database (i.e. “/addUser”). If you remember from the top of the script, the variable “url” allows us to leverage the same-named Node.js module, which provides programmatic access to the URL. We then use the “url” object to access the query string for the new user parameters. Once we have that information, we can leverage code that is nearly identical to the previous article, to create a new document in the collection. So just think of this as adding a row to a database table).

Once the new data has been saved, we then end the response with some HTML, informing the user of the successful data addition, and add a link that allows them to view all data or go to the home page.

Example #7

Example #7 contains all of the utility functions used throughout our code:

utils.isJsonCallback : Returns true if a callback name was provided in the query string
utils.getJsonCallbackName : Returns the name of the callback provided in the query string
utils.wrapDataInCallback : Returns the JSON data, wrapped in the callback function
utils.deleteAllData : Deletes all of the data in the database

Note: At the end of Example #7 you will also see a call to initApp(). This simply starts the HTTP server.

Example #8

So finally, in Example #8 we have the complete code for our working example. You can start the application by navigating to the root of the folder that contains app.js and entering the following command in the terminal: node app.js.

NOTE: On line # 97 of Example #8, I escape the double quotes that are part of HTML element attributes. I did this only because the color-coding of the plugin used to make code more readable was being particularly difficult for some reason. You will likely need to surround that entire string in single quotes, and remove the escape characters: “\”.

Summary

In this article we leverage MongoDB, mongoose and express middleware to create a very basic JSONP API. By using the .get() method of the express object instance, we created functions that respond to specific requests. As a result, we were able to provide the user with functionality to view all data, retrieve all data as a JSONP call, add a user to the database, or delete all data.

Using Mongoose ODM to Connect to MongoDB In Your Node.js Application

Node.js

MongoDB LogoMongoose ODM simplifies the process of connecting to your MongoDB database in your Node.js application and working with the data.

If you are a JavaScript developer, using MongoDB as your backend database is a joy. If for no other reason, you get to think of and interact with data as JSON objects. This serves to solidify the case for Node.js: those of us who live and breathe JavaScript on the client side, can now extend our skill set to include server-side development using the language we love.

The quickest way to get up and running with MongoDB in your Node.js application is to leverage Mongoose ODM. The Mongoose website defines it as a : “…straightforward, schema-based solution to modeling your application data…”. That’s a little deep for me. Suffice it to say, it makes interacting with MongoDB incredibly simple.

In this article, our goal is extremely simple: connect to MongoDB, create a record and then show that record in a web page. While we will barely scratch the surface of what is possible, we will, at minimum, accomplish our modest goal. I’m sure that, as a programmer, you’ll get halfway through this code and realize how much more is possible. You can then take this very basic code, copy and paste it into your own application and then build a more robust solution.

Dependencies

In order to use the code in this article, you’ll need the following installed on your computer:

Installation of these components is beyond the scope of this article, but if you follow the provided links, they will point you in the right direction.

File Structure

  • app.js
  • package.json

For this article, we will need two files: app.js and package.json. In your project folder, create these two blank files. The following sections will explain what to put into them.

Example # 1A

 

In Example # 1A, we have the contents of package.json. I won’t spend too much time on this file. For a more detailed discussion about package.json files you can search this blog for helpful articles. I will point out that the single dependency declared is “mongoose”. When you use node package manager to install dependencies, npm will download version 3.5.7 of mongoose for us.

Example # 1B

In Example # 1B we see the command needed to install the dependencies for our application. In this case, the single dependency declared is “mongoose” version 3.5.7. Once you run this command, you will have everything needed to start writing code.

Getting Started

Open up app.js in your text editor. From this point on, you can copy / paste the code in each example into the app.js (or you can scroll to the bottom of this page and paste the entire code listing in one step).

Example # 2

In Example # 2 we have the variables that we need for our application. Here are the details:

http : a module built into node.js that provides http server methods
mongoose : will be an instance of mongoose, which we listed as a dependency
dbConnString : tells mongoose where the database is running
dbport : tells mongoose which port to use
salesSchema : will be explained a bit later
salesMember : will be explained a bit later

NOTE: I define salesSchema, salesMember and salesMemberDocument at the top of the script because it is a best practice to define all of your variables at the top of your script or function, even if you are not ready to initialize them.

Example # 3

Connecting to the MongoDB Database

In Example # 3, we start out by connecting to the database. The first argument is the connection string, which tells mongoose to find the database. The second argument is a function. Because this connection is an asynchronous event, the anonymous function that we pass as the second argument allows us to safely act upon the completed connection event. Like many Node.js callbacks, this anonymous function takes two arguments: “err” and “res” (which you can of course name anything you want). In the callback, we are interested in the error argument. If the error argument is “falsy”, then we can assume it’s safe to proceed. In this case, we simply log the appropriate console messages.

Defining a Schema

Next up, we define our database schema. Again, just to keep things simple, I won’t go into this in detail. Suffice it to say that we are telling mongoose how the data we will work with will be structured.

Defining a Data Model

Now that we have defined our schema, we call the “model” method of the mongoose object, assigning the resulting value to our variable “salesMember”. When calling mongoose.model, we pass the name of the collection as the first argument (i.e. “Sales”). If the collection does not exist, then it will be created. Simple, simple, simple. The second argument is the schema that will be used, which in this case is the variable “salesSchema”.

Finally, we call the “remove” method of our “salesMember” model, which empties out the collection. This will of course delete the data that we are about to create each time you reload the page. You can safely skip this code block so that each time you run the script and create a new entry in the collection, it persists.

Example # 4

Creating a Document in the MongoDB Collection

In Example # 4, we finally get down to business. Here we overwrite the “salesMemberDocument” variable with a new instance of the “salesMember” model. We pass it an object which represents the data for MongoDB document (you can think of this as a record in a database table and our “Sales” collection as the database table). We then call the “save” method of the salesMemberDocument object. This persists the data.

Example # 5

Starting the Server and Presenting the MongoDB Data

In Example # 5, we create an HTTP server and start it, and then immediately write a “200 ok” header, with the Content-Type of ‘application/json’ (we will present our data as JSON in the browser). Next, we call the find method of the “salesMember” model, passing it an empty object. This tells the “salesMember” model to return everything (i.e. all records in the database table). That method call takes an anonymous function as an argument. We check to see that there were no errors, and if not, we send the result of our find method call to the browser, courtesy of JSON.stringify().

Example # 6

In Example # 6, we have the complete code for our Node.js application. If you paste all of this code into app.js, and be sure that you have successfully executed that file in Node.js, open a browser, and then enter “localhost:5000” in the address bar, you will see the application in action.

Running the Application

In your terminal, navigate to the application folder, and then run the following command:

Example # 7

In Example # 7, we have the JSON data returned in the browser. If you followed the instructions in each step of this article, this is what you should see (although the value of “_id” will differ).

Summary

In this article we learned how to use Mongoose ODM to make a connection to a MongoDB database in a Node.js application. We learned how to define mongoose as a dependency and install it with npm (node package manager). We also covered how to connect to the database, instantiate the schema class, and define a model. In addition, we discussed how to create a new document, save it, and then retrieve it. While this article presented the most bare-bones information on the topic, I hope that it has provided the background you need to get started with MongoDB.

Helpful Links for Mongoose ODM and MogoDB

General

MONGOOSE BASICS: STORING DATA WITH NODE.JS AND MONGODB

Mongoose ODM

http://mongoosejs.com/

http://mongoosejs.com/docs/guide.html

https://devcenter.heroku.com/articles/nodejs-mongoose

MogoDB

http://www.mongodb.org/

http://docs.mongodb.org/manual/

http://en.wikipedia.org/wiki/MongoDB

http://mrbool.com/course/introduction-to-mongodb/323

Organize Your JavaScript Console Logging with a Custom debug() Function

JavaScript

JavaScript LogoEvery console.log() line in your JavaScript code has to be removed before pushing to production. With your own custom debug() method, you can safely leave all of your debug code in-place and just switch them “off” before going live.

The JavaScript console is an invaluable asset in the never-ending quest for sufficiently-tested code. For most JavaScript developers, a day at the office would not be complete without at least a few lines of debug code such as these:

But the problem is that code needs to be removed. That’s fine if it’s just a quick test. But what if there are 20 places in your code where you need to keep track of a value, trace program flow and logic, or test the return value of a function?” Well, that’s a lot of temporary code to keep track of and remember to delete. Even more frustrating is that in a month or two, when business wants more changes, you’ll probably wind up writing the same kinds of debug messages and putting them in the same places, only to have to search your script for “console” once again so that you can remove all of these debug statements before pushing to production.

There is certainly more than one way to skin a cat here, but a simple approach is to write your own custom debug function that shows messages, and knows when it should suppress those messages (i.e. when your code is running in production).

Creating a Custom Debug Function

First, let’s create a couple of functions that do things to objects. We’ll want to debug this code so that along the way, we can check to make sure that the functions are in-fact returning the object that is expected (combineObjects), or making the changes to the object that we pass in (arrayToUpper).

Example # 1

In Example # 1, we have created two simple objects. Let’s imagine that they were created separately somewhere else in our code, and need to be merged in order to create one complete “customer object”. We also have an array that contains the five days of the work week. This array has no functional relation to the two objects. The are all just variables that we can use to test our code.

The combineObjects() function takes two objects as arguments and returns a new object that contains the combined properties of the two original objects. The arrayToUpper() function takes an array as an argument and converts its string elements to upper-case.

For the sake of simplicity, I did not bother doing any kind of verification or type-checking in either method. In the real world, I highly recommend that these kinds of methods contain some kind of verification code at the top so that they fail gracefully.

For example, what if we passed two arrays to combineObjects()? Or what if arrayToUpper() received an array of functions as an argument? This is messy business. I’ve provided a few suggestion on how to create that kind of functionality in an earlier blog post: Validating JavaScript Function Arguments.

So, when you run Example # 1 in your JavaScript console, you will see that we have in-fact created a new object that is the sum of Obj1 and Obj2, and we have changed the array “myArr” so that all of its elements are now uppercase strings. But what I don’t like is that we have written two lines of “test” code that need to be removed at some point (i.e. the two console.dir() statements). I would like to include the testing in our functions so that we can simply call each function, not writing any special code that we need to keep track of and then delete before the production rollout.

Here is the JsFiddle.net link for Exampe # 1: http://jsfiddle.net/UnbVg/

Example # 2

In Example # 2, we have created a variable named “debugMode”. This tells our custom debug function whether or not messages should be output. If “debugMode” is set to “false”, then our custom debug function simply does nothing.

Ok, let’s look at our new “myDebug()” function. This function takes two arguments: a message and a callback. The message should be a string and if so, it will be output in the console. I tend to imagine messages such as “function getAccount started…” or “AJAX success callback fired….” etc. These are messages that your code can send to help “tell a story.”

The purpose of the callback is to allow for more complex messages. For example, you may want to inspect an object at that very moment. So, in addition to the text message, you can pass an anonymous function that contains a line such as “console.dir(myData)”. You could even include your “myDebug()” call inside of a “for” loop, inspecting the state of an object on each iteration of the loop. The sky’s the limit here. In general, I tend to feel that the text message and optional callback are enough for you to provide useful debugging messages for your app.

Example # 3 A

In Example # 3A, we have implemented our custom debug function: “myDebug”. Now we can simply call the functions combineObjects() and arrayToUpper() the way we normally would in our code. The “debugging” code that examines values and outputs informative messages now exists in the actual functions that do the work. When it is time to push this code to production, simply change the value of “debugMode” to “false”, and away we go. One line of code is all it takes to suppress all of our debug messages (see example # 3B below for a demonstration of this).

Here is the JsFiddle.net link for Example # 3A: http://jsfiddle.net/UnbVg/1/

Example # 3B:

In Example # 3B, we have set “debugMode” to “false”, which means that you do not see any debug messages. But to complete our proof-of-concept, we add two console.dir() statements to the end of our code, which demonstrates that the code once again, performed as expected and our custom debug method “myDebug” behaved exactly as designed: no console messages.

Here is the JsFiddle.net link for Example # 3B: http://jsfiddle.net/UnbVg/2/

Summary

In this article, we learned how to create a custom debug function. We discussed the value of minimizing “special” testing code that needs to be tracked and then removed before deploying to production. We also discussed how to design our custom debug function so that it can output text messages as well as execute anonymous functions. We also covered how to implement a very simple “off” switch. This will suppress any debug messages, which is recommended when pushing your code to production.

JavaScript Function Throttling

JavaScript

JavaScript LogoWhen an event such as window.resize() runs more often than you want it to, you can control how many times your event handler runs.

Sometimes events fire very quickly and more often than you would like; window.resize is a perfect example. It’s quite common to assign an event handler that will run every time the user resizes the browser. Unfortunately, however, there is no “resize-end” event. The resize event will fire for every change in pixel. This means that if the user resizes the window 100px, that resize event will run 100 times. But what you usually want is for that event handler to run when the user has finished resizing the window. Since there is no “resize-end” event, we have to use a timeout to imitate the kind of behavior we want.

Example # 1

In Example # 1, we have assigned an anonymous function to the onresize event of the window object. Unfortunately, though, the unordered list is updated every time the window size changes by one pixel. What we want is for the update message to appear after the user has finished resizing the window.

Click here to see the code for Example # 1 in action: http://jsfiddle.net/zWQ8D/

Example # 2

Click here to see the code for Example # 2 in action: http://jsfiddle.net/zWQ8D/1/

In Example # 2, we have created a function named “throttle”. This function will set a timeout of whatever numeric value is passed in as an argument. But every time that same function is called, the timeout, which exists in the global scope, is cleared and reset. Because our window.onresize event calls this function many times in rapid succession, the timeout is constantly re-set, which means that the function passed-in never executes.

The magic happens after the user has stopped resizing the window. Since every call to the “throttle” function sets a timeout, once 250 milliseconds has passed since the last call to the function, the final timeout actually executes. The net result is that the event handler for the window.resize event “feels” as if it only executes once the user has finished resizing the window. What actually happens is that the event handler is passed to the “throttle” function over and over in rapid succession, but our “throttle” function ensures that it only executes if 250 milliseconds has passed since the last time it was called.

Getting Started with the Google Maps JavaScript API – Part III: Adding an Event Listener

JavaScript

Google Maps LogoAdding an event listener to your map is much like using the addEventListener() method on a DOM element.

In Part II of this article, we learned how to add a marker to a Google Map. In Part III of this article, we will learn how to add an event listener to the map. The google.maps object has an event object. One of that object’s methods is called “addListener()”. It’s not too different from the .addEventListener() method that is used to add an event handler to a DOM element in a web page. The google.maps.event.addListener() method takes three arguments:

  • A target
  • An event
  • A callback

The callback can be a reference to a function declaration (or function expression), or an anonymous function. Inside of the callback, you respond to the user’s click.

Example # 1

In Example # 1, we used the the google.maps.event.addListener() method to set up an event handler for when the user clicks the marker on our map. Since we are building upon the demo from Parts I & II of this article, we pass-in “marker” as the first argument, which is a variable we created earlier, that represents an instance of the Marker() object.

Example # 2

In Example # 2, we instantiate the InfoWindow() constructor. The InfoWindow object is a pretty cool feature that provides abstraction for creating a great looking message window on the map. It takes care of rendering the message graphic, positioning it, and adds a nice touch with a shadow. We pass-in an object with the property: “content”. The value of that property is what will be shown in an info window when the user clicks the marker. We then call the open() method of the InfoWindow instance, passing-in the map and the marker as arguments. The open() method needs those objects in order to know where and how to display itself.

Example # 3

In Example # 3, we expand our event handler a bit. In addition to showing the info Window, we also switch the map to Satellite view, zoom it in, and make sure it is centered on the user’s location.

Here is the JsFiddle.net link for this article’s working demo: http://jsfiddle.net/uQ35v/2/

Summary

In this article we learned how to add an event listener to a Google Map. We discussed the google.maps.event.addListener() method, how to instantiate the InfoWindow() constructor, and how to show an info window.

Helpful Links for Adding an Event Listener to a Google Map

https://developers.google.com/maps/documentation/javascript/events

Getting Started with the Google Maps JavaScript API – Part II: Adding a Marker

JavaScript

Google Maps LogoMuch as with the map, creating a marker is done by instantiating the Marker() constructor.

In Part I of this article, we learned how to show a Google Map in a web page, using the Google Maps API. Now in this article, we’ll learn how to add a marker to the map. In Part I we created a function named “successHandler” which was passed as a callback to the getCurrentPosition() method of the navigator’s geolocation object. And inside of this function, we instantiated the Map() constructor of the google.maps object.

Example # 1

In Example # 1, we have the code that adds a marker to the map. When instantiating the Marker() constructor, we pass it an object literal, which then provides settings that the marker needs in order to display properly. The “map” property references the “map” variable that was created earlier in the scope of the “successHandler” function. Once again, we instantiate the LatLng() constructor, providing the user’s latitude and longitude values. Now the “title” property is a string and can be anything you like. It is the text that users will see when they mouse over the marker.

Example # 2

In Example # 2, we have the full-page markup for our working demo. This example builds upon the demo from Part I. So the code is virtually identical, except for instantiation of the Marker() constructor.

Here is the JsFiddle.net link for this article’s working demo: http://jsfiddle.net/uQ35v/1/

Summary

In this article we learned how to place a marker on a Google Map. In doing so, we learned that just as in the case with the map, we instantiate the Marker() constructor. We discussed how settings are passed into the constructor by using an object literal, and how to set the text that is displayed in the marker on mouse-over.

Helpful Links for adding a marker to a Google Map

https://developers.google.com/maps/documentation/javascript/examples/marker-simple

Getting Started with the Google Maps JavaScript API – Part I

JavaScript

Google Maps
Getting a Google Map to show in a web page requires an astonishingly small amount of JavaScript. In this article, we’ll show the user where they are on earth in 12 lines of code.

Since 2005, the Google Maps API has driven one of the most popular web-based applications ever: Google Maps. What I find so appealing about the Google Maps JavaScript API is the relatively small amount of code needed to display a map in a web page. And of course when you do, it’s pretty magical: you are prompted by the browser to allow the page to use your location, and “poof” there you are!

The Google Maps API is a topic worthy of a deep discussion. In this article, we’ll just cover the absolute basics needed to get a map on the page. I chose to limit Part I to this scope because quite often, if you can just “get it to work,” a topic will seem more approachable, and easier to digest.

Ok, let’s show a Google Map on a web page!

Example # 1

In Example # 1, we test to see if the user’s browser supports Geolocation. Specifically, we check to see if the navigator object has a property called “geolocation.” If this property does exist, then we call its .getCurrentPosition() method, passing it a callback. In this case, the callback is a function named “successHandler,” which we will discuss next.

Example # 2

In Example # 2, we have the successHandler function. This is the callback that we have provided to the getCurrentPosition() method. This callback will receive a “position” object as its first argument. That position object holds the data that we will need to provide to the Google Maps API.

Using the latitude and longitude properties of the position object’s “coords” object, we can now instantiate the Map() constructor, which is a property of the google.maps object. When instantiating the Map() constructor, we provide two arguments: a reference to the DOM element in which the map will be displayed, and an object literal, containing display settings:

zoom: Tells the map how much to zoom in when first displaying
center: the “place on earth” on which the map should be centered. Here we instantiate the LatLang() constructor, passing it the latitude and longitude values that were obtained by the geolocation.getCurrentPosition() method
mapTypeId: The type of map to show. The four possible values are: ROADMAP, SATELLITE, HYBRID, and TERRAIN

Example # 3

In Example # 3, we have the full code for this article’s working demo. Here, the exact same code that we discussed in Examples 1 & 2 are used in the context of a full web page.

Here is the JsFiddle.net link for this article’s working demo: http://jsfiddle.net/uQ35v/

Summary

In this article we learned about the absolute basics of the Google Maps JavaScript API. We discussed the need to implement the geolocation.getCurrentPosition() method to get the user’s location and how to provide that information to the Google Maps API to show a basic map on the page. In Part II, we will discuss some of the features that are available when displaying a Google map in a web page.

Helpful Links for the Google Maps JavaScript API.

https://developers.google.com/maps/documentation/javascript/reference

https://developers.google.com/maps/documentation/javascript/tutorial

https://en.wikipedia.org/wiki/Google_Maps

Top 10 JavaScript Links: Native JavaScript

JavaScript

JavaScript LogoThere are a ton of websites that offer information about JavaScript. Some are ok, some are good, some are great. These are the ten websites that I feel offer great information about JavaScript.

This list will change often.


Mozilla Developer Network

MDN JavaScript Home

MDN JavaScript Search

Mozilla describes themselves as: “…a proudly non-profit organization dedicated to keeping the power of the Web in people’s hands.” I believe it, and I believe in them. They have created a ton of helpful articles on JavaScript that are worth their weight in gold.


SitePoint

sitepoint.com

Sitepoint articles are always informative and well-written. It surprises me how actively this site is updated.


Codecademy

codecademy.com

If interactive instruction is your thing, then Codecademy is a great place to dive-in. The interface is clean and the content is quite good.


JavaScript-Garden

http://bonsaiden.github.io/JavaScript-Garden

It’s a bit odd how all of their JavaScript content is one one page. That said, it is a page jam-packed with solid content that addresses some of the most common JavaScript topics that web-developers often find confusing.


javascript.info

http://javascript.info

The coverage is somewhat brief, but overall well-done. The author is Russian and gave-up on the English version of this site because of his frustration with English. There is a link to the Russian version of the site, which offers a great deal of content and is actively updated. If you use Google Chrome, then you can translate these pages on the fly.


Impressive Webs

impressivewebs.com

If you are passionate about JavaScript, this is an excellent resource. There is a nice balance of core JavaScript cocepts and articles about advanced topics.


JavaScript Weekly Archives

javascriptweekly.com

The main goal is to sign-up for the weekly email newsletter. But, you can also just browse past issues. Either way, javascriptweekly.com is a great resource for JavaScript enthusiasts.

Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object — Part II

jQuery

jQuery LogoWhat happens when your JavaScript code depends on not only multiple asynchronous scripts, but also one or more JSONP calls? Once again, jQuery.Deferred() and jQuery.when() save the day.

In Part I of this article: “Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object Part I“, we discussed the complex nature of multiple asynchronous dependencies. In that article, we were able to count on jQuery.when() to pay attention to the resolution of our jQuery.Deferred objects. In this second part, we’ll complicate things even further by adding a JSONP dependency. The “complication” is the fact that the success of the JSONP call requires us to re-think how we will leverage our jQuery.Deferred object’s resolution.

In my opinion, the asynchronous script calls are fairly easy to manage:

But what about a JSONP call? How do we squeeze that scenario into the jQuery.Deferred / jQuery.when() paradigm?

The approach I have taken starts with a variable that is set to an unresolved jQuery.Deferred object. As soon as you create this variable, you can then program around it. In the true spirit of JSONP, you can name your callback whatever you want. If the server supports JSONP, then you can assume that it will call your callback, passing in the much-desired return data.

Here is a pseudo-code walk-through:

Example # 1

In Example # 1, we have the core code that makes this all work. The interesting thing is that the actual JSONP call comes last. What we do beforehand is set up the tools we need to handle this asynchronous event. What makes this scenario a bit special is that you manually resolve the jQuery.Deferred object in the JSONP callback: “foo.resolve()”. This very nicely kicks in the .when() method that is chained to the return value of the jQuery.when() call.

Example # 2

In Example # 2, we have the code for the full working example. It builds upon the full working example from Part I of this article, but the added functionality has no connection to the form validation. The point that is (hopefully) being made here is:

  • This code provides a way to ensure that multiple asynchronously loaded dependencies are loaded before further action is taken.
  • This code checks to see if any of the asynchronously loaded dependencies have already been loaded in the page (possibly by hard-coded synchronous calls or another script).
  • This code allows for the inclusion of an asynchronously loaded JSONP dependency.

Going through the code line-by-line would be repetitive as that was already done in Part I. What might be helpful is to look at the code and see where the approach taken in Example # 1 has been worked into the full working code (Example # 2).

Here is the URL for the full working example: http://examples.kevinchisholm.com/jquery/deferred-and-when/complex-multi-async-dependencies.html

Summary

In this article we learned how to accommodate a JSONP call as an asynchronous dependency. We leveraged the jQuery.Deferred object and the jQuery.when() method to manage and act upon the resolution of the JSONP call.

Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object Part I

jQuery

jQuery LogoThe jQuery.when() method allows you to treat multiple asynchronous script calls as one logical event. But what if there is a chance that one or more dependencies are already loaded?

I just completed a project for a client that involved some tricky script loading logic. I had to use a jQuery plugin and icanhaz.js for templating (I prefer Mustache.js, but the previous developer had implemented icanhaz.js in many of the site’s templates). Now the difficult thing was that I had already written some JavaScript code that lazy-loads touts in the main navigation bar, which appears on every page in the site. So, the situation in hand was as follows:

  • My JavaScript depends on icanhaz.js and a jQuery plugin
  • icanhaz.js is asynchronously loaded further up the page
  • Since icanhaz.js is loaded asynchronously, I can’t assume it’s loaded when my new code runs
  • I don’t want to load icanhaz.js twice

eeesh….

I knew I could count on the jQuery.when() method to handle the multiple asynchronous script loads. Specifically, jQuery.when() can treat two or more asynchronous script load events as one event. The completion of the multiple events can represent one completed event, which can be used to tell the rest of your code: “hey, we have what we need, let’s proceed.” But at first I was not sure how to abstract the details of whether or not a script is already loaded. For example, If icanhaz.js has already been loaded in the page, I don’t want to waste time by loading it again (and potentially cause unexpected behavior because it loaded twice).

So I decided to leverage the jQuery.deferred constructor.

In short, for each script that needed to be loaded (i.e. each dependency), I wrote a function that checks to see if that script was already loaded. If so, then the function returns a resolved jQuery.deferred instance. If not, then I simply use the jQuery.when() method to wrap a jQuery.getScript() call, which returns an unresolved jQuery.deferred instance. So either way, my function returns a jQuery.deferred instance. This is perfect because jQuery can easily understand (and act upon) the “state” of a jQuery.deferred instance. And most importantly, jQuery can view multiple jQuery.deferred instances as one “event”.

“…..hmmmm Idunno Kevin, this is all starting to sound a little convoluted to me!”

I had similar feelings when I was working this out in my head. But once I fired up my JavaScript console, and started testing the code, it was not only easy to understand the logic, it worked flawlessly (serious kudos to the jQuery folks; these are awesome features).

So, for this article, I decided to use Mustache.js and the jQuery validation plugin as my dependencies. Mustache.js will be used to build the form and the jQuery validation plugin will provide form validation.

Example # 1

In Example # 1, we simply have the markup for the page. Not too much going on here: a page wrapper and two header elements. What it does illustrate is that the form and the validation you see when you run the final working example is all handled by our two dependencies: Mustache.js and the jQuery form validation plugin.

Example # 2

Now, in Example # 2, we have provided two constants which are simply the URLs for the script calls that we (might) have to make. This is a pattern that I like to follow, which can help to minimize clutter in your implementation code; make values that will never change constants and put them all in one coherent place.

The variable “data” simply holds an object literal that will be used by Mustache.js to populate the template, and the variable “template” is the string used by Mustache.js to create the template. (Notice the values inside of the double curly brackets: “{{}}”; these all map to properties in the “data” object.)

Example # 3

In Example # 3, we have a function that always returns a jQuery.deferred instance. The if/else statement provides two possible outcomes: Mustache.js is already loaded in the page or Mustache.js is not loaded. We test for the existence of window.Mustache (and the value of its “name” property) in order to determine the answer. If Mustache.js is already loaded, then we simply return a resolved jQuery.deferred object. If it is not, we then return a call to jQuery.when(), passing a jQuery.getScript() call as an argument. The jQuery.when method returns a jQuery.deferred instance that is in an “unresolved” state until the getScript() call completes.

The key point here is that even though in this case our function returns an un-resolved jQuery.deferred instance, the fact that it is a jQuery.deferred object is all we need.

So there is no need to walk through the function that does the same thing for the jQuery validation plugin; the logic is exactly the same. If you look at the code for the full working example at the end of this article, you’ll see that the only difference is the URL for the script that is loaded, and the way in which we determine if the plugin exists (i.e. we check for the existence of a property of the jQuery.prototype object named “formval”).

Example # 4

Now here in Example # 4, we create two variables. Both variables become a jQuery.deferred object because in each case, the variable is being set to the return value of the methods we just discussed in Example # 3: each of these methods returns a jQuery.deferred object. Again, these objects are in either a “pending” or “resolved” state, depending on whether or not the specified script was loaded.

Example # 5

{ //build the markup fom the template (uses Mustache.js) var form = Mustache.render(template,data); //inject the form $(‘#container’).append(form); //setup the form for validation (form validation plugin) $(‘#testform’).formval(); });

In Example # 5, look very closely at the first line: $.when(formValIsLoaded,mustacheIsLoaded). Essentially, this line says: “When the two arguments resolve…” that is, when both of these argument’s “state” changes to “resolved”. Now this is important because it’s treating the resolution of two or more events as one event. For example:

Event-A.completed + Event-B.completed = Event-C.done

So, this $.when() method will return when all of the arguments have a “resolved” state. Since the return value is also a jQuery.deferred object, then we can utilize its .done() method. We pass an anonymous function as an argument to the .when() method. This function will execute when all of the arguments of the .when() method are resolved.

Once we are inside of the anonymous function, we can be confident that our dependencies are loaded. At this point, there are just a couple of things left to do:

  • Create our form, using the Mustache.render() method, and inject it into the DOM
  • Set up validation using the jQuery.validation plugin

So, here we have it, the end result of all this work we have done, which is a simple one-field form. When you view the full working example (see link below), you can click the submit button to see the validation fail, which will cause the error message to show. And the label for the name field, the submit button’s text and the error message have all been supplied by the “data” variable in our code, which if you remember, is an object literal that contained all of those string values.

Example # 6

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

Here is the JsFiddle.net link for our full working example: http://jsfiddle.net/Ebj4v/5/

Final Proof of Concept

In the links that follow, we have added script tags to the code. In the first two cases, one of our dependencies is pre-loaded. In the third case both are pre-loaded. Chrome does not like the mimetype of the scripts as they are served from github.com, so please view these examples in FireFox. Open up your JavaScript console when viewing the examples. In each case, you will see a message indicating which dependency was pre-loaded. In all three cases, the resulting behaviour is the same: our code checks to see if a dependency is loaded, if so, great, and if not it loads it.

Mustache.js preloaded: http://jsfiddle.net/Ebj4v/6/

jQuery.validation plugin preloaded: http://jsfiddle.net/Ebj4v/7/

Both Mustache.js and jQuery.validation plugin preloaded: http://jsfiddle.net/Ebj4v/8/

Summary

In this article we learned how to solve a complex script-loading scenario. In doing so, we discussed the jQuery.deferred() constructor and jQuery.when() methods, learning how they can be leveraged to create an if/else logic so that we can determine whether or not a script was loaded, and then depending on the answer, take the appropriate action.

Helpful Links for jQuery.deferred and jQuery.when

jQuery.deferred

http://api.jquery.com/jQuery.Deferred/

http://api.jquery.com/category/deferred-object/

http://blog.kevinchisholm.com/javascript/jquery/using-the-jquery-promise-interface-to-avoid-the-ajax-pyramid-of-doom/

jQuery.when

http://api.jquery.com/jQuery.when/