JavaScript Callback Functions – The Absolute Basics

Callbacks are a critical tool for properly handling asynchronous events in JavaScript.

Timing is one of the most difficult techniques to master in JavaScript. At first, many look to the setTimeout() method to address the asynchronous nature of JavaScript. But that is most often not the best approach. The concept of a callback function is one of the things that makes JavaScript such a special language.

In order to understand callbacks, it is important to be aware that functions are first class citizens in JavaScript. This means (among other things) that a function can be passed as a value to another function. The upside to this is the fact that if you call function A, and pass it function B as an argument, then inside of function A, you can execute function B. That’s really what it all boils down to: You call a function, and pass it another function, and inside of the first function, when an event that you need to complete has completed, then you “call back” to the function that was passed in.

While you can pass a named function as an argument, quite often you will see an anonymous function passed. Before we demonstrate a callback function, let’s demonstrate why they are so helpful in JavaScript.

Example # 1

PHP FIle:

Client-side JavaScript:

In example # 1, we have two chunks of code: A server-side page that sleeps for three seconds, and then returns a JavaScript file. That JavaScript file simply outputs a message to the console.

When the script loads, it outputs a message to the console (message # 1). We want that message to be output before the 2nd message. The problem is that the script loading process is asynchronous; it could take 200ms, it could take five minutes. I’ve forced the PHP page that returns the JavaScript to “sleep” for three seconds, to exaggerate the effect. But the bottom line is: we don’t know how long that script loading process will take, which means that we have to find a way to execute message # 2 only after the script has finished loading.

Here is a JSFiddle link for Example # 1: http://jsfiddle.net/CZeLv/

Example # 2

In Example # 2, we pass an anonymous function to the getScript() method. Inside of getScript(), we take advantage of the fact that any dynamically loaded script element has an “onload” event. We assign that event to the callback that was passed-in. This means that when the script has successfully loaded, we execute the callback. As a result, we have complete control over the timing of events, even though the entire process is asynchronous. What happens is that message # 1 first first, and them message # 2. This is what we want.

Here is a JSFiddle link for Example # 2: http://jsfiddle.net/dfCM2/

What if the script that we are loading has properties and methods that we need to act upon once the script is available? In example # 3, we demonstrate how using a callback allows us to call a method that does not exist before the script is loaded, but we are able to control the timing of when it is called, so that it works every time.

Example # 3

PHP File:

Client-side JavaScript:

In example # 3, after the PHP file “sleeps” for three seconds, it adds a new method to the window object. That method returns a secret word. We need access to that secret word in our page, but we need to make sure that we don’t try to call the method getSecretWord() until it is available. By passing a callback to the getScript() function, we yield control to getScript() and basically ask it to fire our callback for us. Inside of getScript(), the script’s onload event is assigned to the callback, which means we only attempt to execute getSecretWord() once we know for sure that it exists (because the script’s onload event fired).

The important thing to keep in mind here is that if the script we are loading takes 5 minutes to return, or never returns, it does not matter. Our callback will only fire when that script successfully loads. While it is loading, the user still has complete access to the browser. That is really important.

Here is a JSFiddle link for Example # 3: http://jsfiddle.net/fAn4g/

Summary

In this article, we covered the very basics of JavaScript callback functions. We learned that functions are first-class citizens in JavaScript, and can be passed around to and from functions. We looked at an example of why callbacks are so critical to the JavaScript language and how they are an excellent tool for working around the asynchronous nature of the language,

Helpful Links for JavaScript Callback Functions

http://recurial.com/programming/understanding-callback-functions-in-javascript/

http://www.impressivewebs.com/callback-functions-javascript/

http://javascript.about.com/od/byexample/a/usingfunctions-callbackfunction-example.htm

jQuery Plugin Authoring – The Absolute Basics – Part II

jQuery Logo

Once you have jQuery plugin basics down, it’s time to implement some best practices

In the previous post “jQuery Plugin Authoring – The Absolute Basics – Part I”, we to a detailed look at the architecture of a jQuery plugin. Now that you understand the building blocks, let’s discuss a few best practices. These techniques are considered standard for quality jQuery plugin authoring, and will dress you for success.

Protecting the Dollar Sign

Most jQuery consumers associate the dollar sign with jQuery. But that dollar sign is simply a shortcut to the jQuery object, which is a property of the window object. You could write all of your jQuery code without ever using the dollar sign, and simply “jQuery” instead. But most people prefer the dollar sign because it is of course quite a bit easier and faster to type.

But jQuery offers a “no conflict” mode that allows another library to take over the dollar sign. It is considered best practice to anticipate this scenario and pass the global jQuery object into the immediate function that wraps your plugin. This way, inside of the nice and safe sandbox of your plugin, you can use the dollar sign all you like, without the slightest concern for how it is being used in the global context.

Example # 1

In Example # 1, we pass the global jQuery object into the immediate function. The immediate function takes that jQuery object as “$”, so from there on we are free to use the dollar sign safely, even if jQuery is in no-conflict mode.

Chainability

Method chaining is a popular technique in JavaScript. Many web developers use this technique when they leverage jQuery without even knowing it. How many time have you seen something like this:

$(SOME PARENT).find(SOME CHILD).CSS(“prop”,”val”).click();

What signifies the chaining activity is the fact that we have only one reference to the jQuery collection returned by $(SOME PARENT). Since each method used returns the jQuery object, we can use that return value to invoke another jQuery method, and so on. This is called “Chaining” method calls together.

It is considered best practice to allow method chaining when authoring your own jQuery plugin. Doing so is quite simple; you just need to return the jQuery object from each method.

Example # 2

In Example # 2, we return “this” from our plugin function. It’s important to note where the return statement is. Because the return statement occurs as the last line of code in our plugin’s function, the jQuery collection object is returned to the next method that wants to “chain”, without the need to re-state a jQuery collection.

Example # 3

In Example # 3, we have an example of method chaining in jQuery. Note that $(‘a’) only occurs once. That call to jQuery returns a jQuery collection object, which is returned from our jQuery plugin. As a result, the .attr() method can “chain” onto that return value and function properly.

Example # 4

In Example # 4, we have an even more complex example of method chaining. First we invoke “myPlugin”, and the the jQuery methods: .attr(), .css() and .click()

Here is a fully working JSFiddle.net link that demonstrates the best practices we have covered in this article. Be sure to click a few of the links to demonstrate the method chaining from example # 4:

http://jsfiddle.net/fTA95/

Summary

In this article we discussed a few jQuery plugin authoring best practices. We covered how to safely use the dollar sign in your plugin code, even when jQuery is in no-conflict mode. We also covered how to implement method chaining.

Helpful Links for jQuery plugin authoring

http://docs.jquery.com/Plugins/Authoring
http://stackoverflow.com/questions/12632382/jquery-plugin-authoring-and-namespacing

jQuery Plugin Authoring – The Absolute Basics – Part I

jQuery Logo

You know a little jQuery, you have used a few jQuery plugins, and now you want to write your own jQuery plugin. Don’t worry, it’s no big deal. In fact it’s fun.

If you have been putting off authoring your first jQuery plugin, it’s time to wrap a bandana around your head, fire up “The Eye of the Tiger” by “Survivor” and figure out how to defeat Apollo Creed. Sorry, for the cheesy 80s reference, I couldn’t resist.

But seriously, it really is no big deal. The most important thing is to get a firm grip on the fundamentals. That part is serious. If you don’t understand what you are doing from a jQuery-architecture standpoint, then you will quickly find yourself in a quagmire of muck and filth, and you don’t want that.

In this article we will discuss the absolute basics of how to author a jQuery plugin:

  • Wrapping your plugin in a self-executing anonymous function
  • Extending the jQuery prototype,
  • Iterating over each element in the jQuery collection returned by your plugin.

This is the big stuff. Once you get your noggin around these concepts, the fun can begin.

A note about Self-executing anonymous functions

These are otherwise known as “immediate functions”. An immediate function is simply a function that is wrapped in parentheses, and followed by a pair of parentheses:

You can learn more about immediate functions in my blog post:Immediate Functions in JavaScript – The Basicsas well as my blog post:Using an Immediate Function to Create a Global JavaScript Variable That Has Private Scope

The main point here is to make sure you are comfortable with the concept of an immediate function in JavaScript. It’s important to do before reading further.

Where does my jQuery plugin code go?

Good question. The answer is: In its own file. By convention, you’ll want to create a JavaSript file named jquery.myPlugin.js. Then you’ll need to reference it just as you would any other JavaScript file:

Just make sure you reference jQuery before you reference your plugin.

For simplicity sake, we will reference our jQuery plugin via a set of SCRIPT tags, right in the page (that is perfectly valid, but definitely not practical).

Example # 1

In example # 1 we have the absolute bare-bones code needed for a jQuery plugin. Here are the important points to consider for example # 1:

Wrap your jQuery plugin in an immediate Function

This is considered a best-practice and for good reason. Taking this approach allows you to create as many variables as you need in your plugin, without polluting the global namespace. Don’t overlook this, it allows you complete freedom with regards to the number of variables you need to create, and sandboxes all of these variables very nicely.

Again, an immediate function is simply a function that is wrapped in parentheses, and followed by a pair of parentheses. It fires right away when the JavaScript is evaluated, you don’t need to (and cannot) call the function. It just fires right away and whatever code you implement in that function executes. It’s a great way to provide private variable scope to some code without a whole lotta fuss.

If you are still having a tough time with the concept of immediate functions, stop, do a google search for JavaScript Immediate Function, learn it, live it, ask it out on a date, marry it, and then come back here to keep on reading.

https://www.google.com/search?q=javascript+immediate+function

(I’m serious about this immediate function thingy)

Your jQuery plugin becomes a property of the jQuery prototype object

jQuery is a function. Actually, the code in jQuery follows the factory pattern and returns a function that in-turn returns different kinds of things, depending on what you pass into that function. Most of the time, it returns an HTML collection wrapped with jQuery (hence a jQuery collection object), but again, the actual return value depends on what you are passing in.

Every JavaScript object has a prototype property, this includes functions. jQuery exposes its prototype property as “fn”. So, you simply assign your plugin to be a property of that “fn” object. Once you have done that, jQuery now has a new method that is YOUR plugin.

Now you can do this:

Inside of your plugin, the JavaScript keyword “this” is already a jQuery object

Most people know that inside of a jQuery callback, “this” usually refers to the current native DOM element that is being iterated over. When you wrap “this” in jQuery, it becomes a jQuery object. So, we often refer to “this” as “$(this)”.

Inside of your plugin, there is no need to do that because the JavaScript keyword “this” is already a jQuery object. If you refer to “this” as “$(this)”, it’s not going to kill anyone, but it is not necessary and just uses more memory than is needed.

Your jQuery plugin returns a jQuery collection

What your jQuery plugin returns depends on the CSS selector that was passed-in. For example, if you do this: $(body).myPlugin(), your jquery plugin will return a jQuery collection that has exactly one element: the BODY tag of your document (unless of course you have more than one BODY element in your page, which would be a bit of a head-scratcher). So, if you have an unordered list that has for example three items, and you invoke your plugin like this: $(ul li).myPlugin(), then your plugin will return a jQuery collection that contains three elements.

Use this.each() to iterate over all of the elements that are returned by your jQuery plugin

jQuery’s .each() method is a lovely little tool that allows you to iterate over a jQuery collection and “do something” to each element. Keep in mind that a jQuery collection can always contain exactly one element, and when it does, then the .each() method will run once. But when a jQuery collection contains multiple elements, then the .each() method will run once for EACH element in that collection.

When you use the .each() method, you pass in an anonymous function, and inside that function you have access to the current element that is being iterated over. It is here that you will need to wrap “this” with jQuery if you want it to be a jQuery object: Use $(this) for the jQuery object that represents the current element, or simply “this” for the native DOM element implementation. This anonymous function takes as its first argument the index of the current element. This is surprisingly handy: what if you want to know if this the the first element in the collection? or the last? That index number will help you with that task.

Now you are ready to write some awesome jQuery plugin code

Thanks for hanging in there. The preceding details were important. I know you are anxious to write some code, but understanding the outer architecture of a jQuery plugin is critical. If you do not understand what was just covered, then you will quickly be awash in spaghetti code that is not working right and will be difficult to debug. I promise you.

Example # 2

In example # 2, we invoke our jQuery plugin. We wrap it in a $(document).ready() call so that it only fires once the document is ready.

Invoking our plugin is as simple as $(CSS SELECTOR).myPlugin().

This is because our plugin is a property of the jQuery prototype object, which makes it a completely valid jQuery method. Nice.

Example # 3

In example # 3, we see how our plugin can behave differently depending on what we pass into it. In each case, the jQuery collection object returned by our plugin will differ, depending again on what CSS selector we passed-in.

Example # 4

In example # 4, we have included some implementation code so that our jQuery plugin actually does something. I this case, for each element returned in the jQuery collection, we change the CSS so that the element’s color is green, the background color is yellow, and the font is “Comic Sans”. Not too pretty, but just enough so that when we run the code, we can see that our plugin is working perfectly. More importantly, if you vary the CSS selector that is passed-in, you will see that our plugin behaves differently in each case (i.e. the HTML elements that become green with yellow backgrounds and Comic Sans font will vary).

Full Working Code for this Article
http://jsfiddle.net/wdUtL/

Full Working Code for this ArticleWith Comments
http://jsfiddle.net/ewTez/

Summary

In this article we discussed the absolute basics of how to author a jQuery plugin. We covered how to wrap your plugin in a self-executing anonymous function, how to extend the jQuery prototype, and how to iterate over each element in the jQuery collection returned by your plugin.

This example provided in this article was very simple. The main purpose of the article was to provide the overview needed so that you understand how a jQuery plugin is constructed, how it works at the most basic level, and importantly how the value of the JavaScript keyword “this” will vary a bit, depending on where you are in the code.

With a firm understanding of how a jQuery plugin is constructed, we can move on to best practices and more intermediate jQuery plugin authoring techniques.

Helpful Links for jQuery plugin authoring basics

http://docs.jquery.com/Plugins/Authoring

http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/

http://blog.kevinchisholm.com/jquery/jquery-each-method/

 

What is the Difference Between Scope and Context in JavaScript?

In JavaScript, scope and context are not the same thing, and you should understand the difference between them. Fortunately, the answer is short and simple.

When interviewing front-end developers, I usually try to include a question about Scope and Context in JavaScript. I always ask what the difference is. The answers I get often surprise me. It seems that even those with some experience have difficulty answering this question.

The answer is short and simple: Scope pertains to the visibility of variables, and context refers to the object within which a function is executed.

Scope

Scope has to do with the the visibility of variables. In JavaScript, scope is achieved through the use of functions. When you use the keyword “var” inside of a function, the variable that you are initializing is private, and cannot be seen outside of that function. But, if there are functions inside of this function, then those “inner” functions can “see” that variable; that variable is said to be “in-scope”. Functions can “see” variables that are declared inside of them, and any that are declared outside of them, but never those declared inside of functions that are nested in that function. This is scope in JavaScript.

Context

Context is related to objects. It refers to the object within which a function is executed. When you use the JavaScript keyword “this”, that word refers to the object that the function is executing in.

Scope refers to the visibility of variables, and scope refers to the context within which a function is executed.

For example, inside of a function, when you say: “this.accoutNumber”, you are referring to the property “accoutNumber”, that belongs to the object within which the function is executing. If the object “foo” has a method called “bar”, when the JavaScript keyword “this” is used inside of “bar”, it refers to “foo”. If the function “bar” were executed in the global scope, then “this” refers to the window object. It is important to keep in mind that by using the JavaScript call() or apply() methods, you can alter the context within which a function is executed, which in-turn changes the meaning of “this” inside of that function when it is executed.

Summary

In my opinion, it is critical to understand the difference between scope and context in JavaScript. As soon as you have to write or edit even intermediate-level JavaScript, these two topics become very important. If you don’t understand the difference between scope and context, your ability to comfortably and confidently write / edit JavaScript will never improve. This is an important topic. The good news is, it’s not that difficult to understand and once you get it, you’ve got it.

Helpful Links for understanding the difference between scope and context in JavaScript

Understanding Scope in JavaScript – Function Level Scope | Kevin Chisholm – Blog

Understanding Context in JavaScript – Object Literals | Kevin Chisholm – Blog

 

 

Making Your JavaScript Code Easier to Understand: Object Literals

When it comes to organizing your object literals, there are multiple approaches you can take

Object Literals are a very useful feature of JavaScript. They allow you to easily build structures of data or functionality (or both mixed together), without too much fuss and drama. The syntax is simple and they make it easy to name-space your code. But, when your object literals start to grow in size, they can become a bit difficult to manage. And, it can sometimes make your code harder to follow.

In the next few examples, I will cover a couple of  alternate ways to organize your JavaScript Object Literals. This can make your code easier to manage and understand.
Example # 1

In Example # 1, we have an object literal that has been assigned to the variable “mathFuncs”. This object has three members: “add”, “subtract” and “multiply”. Each is a function. This is not too bad, but what if each function was tens or even hundreds of lines of code? The entire “mathFuncs” object itself would grow to become thousands of lines long. This can become unwieldy. Also, if while making edits, one semicolon gets knocked out of place, the entire object is likely to become defective, which will pretty much kill the script.

Example # 2

In Example # 2, “mathFuncs” is initially one line of code: an empty object. We then extend the object by adding more properties. In this case, the three properties we add are “add”, “subtract” and “multiply”. Functionally, there is no difference between this approach and Example # 2. These anonymous functions will perform no differently. What is different is that the code is a little bit easier to follow. First you see that “mathFuncs” is an empty object, and then we add properties to it. These properties are all functions, so they should be referred to as “methods”. Also, if you have a bug in one of the anonymous functions, it is less likely to break the entire script, and could be easier to track down.

Since these functions are very small, there is yet another level of optimization that we can apply:

Example # 3

In Example # 3 we tightened up the first three functions because there is so little going on in them, so it’s no harm to make them all one line each. Again, it’s just easier for someone else to quickly read and understand. We added two new properties, both anonymous functions as well. Since these are bigger functions (let’s pretend they are each 50+ lines of code), we put them last so that they are a bit out of the way, and we only have to see all that implementation code if we care to.

This is all a matter of preference. From time to time, I think that not everyone realizes that there are options when it comes to object literals and how you choose to write them out. The approach taken in Example # 1 is fine, especially when the objects are small. But when you have many properties in your object, and those properties are anonymous functions that contain tens or hundreds of lines of code, it can make your logic hard for someone else to follow.

Summary

There are many ways to skin a cat, and as many ways to organize your JavaScript code. The purpose of this post was to offer a few suggestions that can make your object literals a little bit easier to read, especially for someone else who, in the future, might have to read, understand and then make changes to your code.