Share Tweet Reccomend

JavaScript: Apply and Call Methods

In what follows we are going to look at 2 different JavaScript methods used when dealing with functions: apply and call. Apply and call are essentially used to call a function elsewhere in your code * using the arguments of another function as the arguments for calling that other function *. So if you were inside a function and needed to do some sort of process that figured out something about the arguments of your current function, you could use apply or call. The only real practical difference is that “apply” passes the arguments as a single array and “call” passes each of the arguments individually as separate arguments.

Let’s take a look at the following…

function calculateMyTotal(number1, number2){
    return number1 + number2;
}

function sumArguments1(num1, num2){
    return calculateMyTotal.apply(this, [num1, num2]);  //passing in array
}

Here you can see we have called the calculateMyTotal function and have used the arguments of the current function as the arguments to pass into another function. The “this” just means this current function — in this case, sumArguments1. Another powerful and useful feature of using the apply and call methods is the ability to change what the “this” pointer points to. When you use apply and call, “this” becomes the function/object you are passing into the apply and call methods. It may not be immediately apparent from our simple demonstrations, but it can be very useful if used properly in other instances.

So, getting back to our example, if we were to do…

sumArguments1(1,2);
sumArguments1(4,8)

The results would be 3 and 12.

Because JavaScript functions all have an arguments property (which is a sequential array-like object of the arguments passed into the function), you could just as easily say…

function sumArguments1 (num1, num2) {
    return calculateMyTotal.apply(this, arguments);    //passing in arguments object
}

You don’t even necessarily have to use apply on “this” current function. What if we had another function…

function favoriteNumbers(num1, num2) {
    return 'My favorite numbers are ' + num1 + ' and ' + num2;
} 

Now, elsewhere in your code, we could pass favoriteNumbers in as the function. You could say…

calculateMyTotal.apply(favoriteNumbers, [3,4]); // needs pass in array as 2nd argument 

This will give you 7 even though favoriteNumbers is a function that has nothing to do with adding 2 numbers together.

The call method is similar, but instead of using an array as the second argument, you have to use each argument individually. So if we were to do the same as our previous example we could do…

calculateMyTotal.call(favoriteNumbers, 3,4); // passing each number as a separate argument

Which will also give us 7. It’s the same result, but which one you want to use depends on what kind of function you are trying to pass into apply or call (or it might even come down to personal preference). Either way, you can see that you can use a function’s arguments and apply them to another function, or call another function using them.

Share Tweet Reccomend

Backbone.js Routers

In what follows, we are going to look at Backbone.js routers. Routers are a great place to start whenever you begin developing a Backbone application (or any application for that matter) because you can figure out what URLs and sections your app will need and add hooks in your code to respond to them. It helps define application structure, much like a flow chart would.

The files for demo and download for the following discussion can be found below if you’d like to follow along…

View Demo Download Files

Backbone.js uses routers to execute certain actions when a user goes to a certain URL within a Backbone application. Backbone applications all use routes that follow a # character in the URL. The # might be familiar to you if you’ve ever used it as a named anchor to link to part of the current document without going to a new URL. This is very prevalent in pages that have tables of content at the top (e.g. like in Wikipedia articles), where the links at the top take you to a place on the same page further down. That’s what’s going to happen with Backbone. We’re going to stay on our same page, but we’re going to set up our JavaScript such that Backbone listens for the user going to these links. When the user clicks on different links within the application, instead of going to a different place on the page, we’ll be executing different portions of JavaScript in our code. That’s how a “client-side JavaScript application” essentially behaves.

Read More »

Share Tweet Reccomend

Concatenate and Compress JavaScript with UglifyJS

The benefits of using something like RequireJS to asynchronously to load your project’s JavaScript was discussed previously. However, if you wish to load JavaScript in the more conventional way (that is, just sticking a script tag or tags in the browser) there are quick and lightweight ways to make this an efficient and viable option as well. These methods involve concatenating and compressing (minifying) your JavaScript files into one script file. At the end of the process you’ll only need to end up loading this one large script file (which is a lot quicker than loading numerous smaller scripts file) Additionally, if you concatenate your JavaScript files in a particular sequential order, you can easily make this a way to manage your dependencies… you just need to make sure that you load the dependency libraries before you load the libraries that require them. The tools we will look at in what follows makes this a fairly simple process.

To accomplish this in my workflow I use something called UglifyJS. It’s a simple package that runs in a Node.js environment. Node.js is a platform that allows you to run JavaScript system level applications on a server environment (or in this case, on our local machine). We can open our terminal and type something like “node myJavaScriptFile.js” and run some JavaScript we have written to do all kinds of neat stuff… all outside of the browser. So first things first, go and download and install Node.js if you haven’t already.

After that navigate to the directory where node is installed and run…

npm install uglify-js -g

nmp (which stands for Node Package Manager, is a way of quickly installing the latest version of Node applications). You may have seen this elsewhere with Python’s pip command or Ruby’s gems. The -g parameter stands for global, which will enable you to run UglifyJS from anywhere on your machine.

Now what you can do is simply run the command according to the following format in the directory where your JavaScript files are…

uglifyjs -o scripts.js javascript-file1.js javascript-file2.js javascript-file3.js

In the example above, javascript-file1.js, javascript-file2.js, and javascript-file3.js will all be concatenated and compressed into a file named scripts.js file in the order in which they were set. So following this convention, you can load your dependencies where they are important in your JavaScript projects. Backbone.js, for example, has a hard dependency on Underscore. So you’d want to add Underscore *before* you’d add Backbone if you were doing a Backbone project. Also, a lot of times developers like to have jQuery available to them in their Backbone models, collections and views. So we could add jQuery into our list of files as well resulting in something like the following…

uglifyjs -o scripts.js underscore.js jQuery.js backbone.js

** Note that all of these files (underscore.js, jQuery.js, backbone.js) have to exist within the directory that you’re running the command from. scripts.js will be created if it doesn’t exist and overwritten if it does.

But whatever JavaScript you decide you need to include, all you have to do once the UglifyJS build process is complete is load the scripts.js file in your HTML. You can name this file whatever you want (it doesn’t have to be scripts.js). What I usually do in my workflow is set up a .bat file (and call it build-js.bat or something) that has all of my files and their dependencies set in the order that I need them. Then when I need to deploy my JavaScript to production I just run the .bat file.

So whichever way you choose to do it (either using the asynchronous module definition (AMD) pattern using something like RequireJS or using a tool like UglifyJS or using another similar solution) there are definitely good ways to load your handle your project’s JavaScript JavaScript in an efficient and effective manner.

Share Tweet Reccomend

Loading JavaScript with RequireJS

RequireJS according to it’s website is…

…a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

In this section we will walk through some basics on how and when you can use RequireJS and discuss some of the benefits you may get from doing so. Personally, I’ve always thought that RequireJS can be a somewhat confusing concept to wrap one’s head around at first. I think this may have mainly been because a lot of times RequireJS is demonstrated in the context of a big web application project and it can sometimes be difficult to follow what its responsibilities are in the midst of numerous files doing all sorts of different things. So we are going to start off very very slowly (we’re just going to use it to load a couple JavaScript files) and we will look at doing more in depth things later on.

You can grab the demo files below from this tutorial if you want to follow along…

Demo Files

Why Use RequireJS?

Why would you want to use RequireJS? Well there can be a number of reasons but at the bottom of it all the main purposes are to keep your JavaScript nice and organized, fast-loading, and easily extendable. If you are just doing a little bit of jQuery for a bit of enhancement on the front end of a website, then maybe RequireJS is a bit overkill for your purposes. However, the real value of RequireJS comes in when you start to develop larger client-side web applications that have numerous JavaScript files, with different dependencies, all interacting with one another..

Often times, if you look in an HTML document of you’ll see something like the following…

Read More »

Share Tweet Reccomend

jQuery: What’s the Difference Between $(this), $this, and this?

When doing jQuery development and looking at the code in other people’s jQuery functions and plugins you’ll eventually see that different developers will use different syntaxes in different places. This is probably most apparent in the use of the term “this”. Sometimes you will see this. Other times you will see $(this) and still other times you will see $this. What is the difference between all of these and when should you use each one?

The this pointer in JavaScript refers to the current object that we are running our code inside. In JavaScript everything is an object, so the scope of this is always changing.

Let’s say we had a page like one that is shown below…

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
</head>
<body>

<div id="one" class="myClass">One</div>
<div id="two" class="myClass">Two</div>
<div id="three" class="myClass">Three</div>
<div id="four" class="otherClass">Four</div>

<script type="text/javascript">

</script>

</body>
</html> 

Now in the <script> section let’s add some jQuery to loop through all of the elements with the “myClass” class (all the <div>’s on the page. As many know, to do this we use the jQuery each method. Inside of each we can use the pointer “this” to refer to the current DOM element in set of elements we are on.

$(document).ready(function() {
    $('.myClass').each(function(){
       // do something with this here
    });

});

Let’s use the native JavaScript function getAttribute() to get the id attribute of each element.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log(this.getAttribute('id'));
    });

});

If we look in our console, we can see that the text one, two, three appears (the id attributes of each DOM element that has “myClass”). So everything works as expected.

But as you know jQuery also has a method for getting an attribute: the attr() method. So let’s try it with that.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log(this.attr('id'));
    });

});

However if we look in our console we get an error.

Uncaught TypeError: Object # has no method ‘attr’.

Why is that? We know we are referencing the correct DOM element. Well, it’s because we haven’t wrapped this (the current DOM element) in jQuery so that we can call jQuery methods on it. That’s really the big distinction between $(this) and this. They both refer to the same object. However, if you want to use any jQuery on the object, it must be wrapped in a jQuery object as $(this) like so.

$(document).ready(function() {
    $('.myClass').each(function(){
       console.log($(this).attr('id'));
    });

});

The reverse is also true. Because the $() is a jQuery wrapper, you cannot call native JavaScript on it. So $(this).getArribute(‘id’) also wouldn’t work.

So that’s the big thing to remember. If you want to call a jQuery method on your object, wrap it it $(). If you want to use a native JavaScript method, don’t wrap it in $(). Just use plain ol’ this

What about $this?

$this is a little different because it’s actually just a variable that uses the $. It has no inherent relation to jQuery. It would be no different than JavaScript variables named $corn or $carrots. You just was easily say var $this = “My pet cat is named Mittens.”; It’s just a variable with the dollar sign in it. JavaScript allows characters like this in variable names. The reason that you see use of $this inside of jQuery plugins is that often times developers in the global scope inside of their plugin will say something like:

var $this = $(this);

That way they can always have a reference to the object on which the plugin was called. The scope of “this” will change in any methods used inside the plugin so it’s always good to have a global variable (that is, global inside the plugin scope) which you can refer to the object on which the plugin was called. But the important thing to remember is that $this has no inherent relation to jQuery. It’s just a variable like any other.

Personally however, I never really liked naming the DOM element object using that convention. I always used var object = $(this); as can be seen in some jQuery plugins I have written. I figured with all the this’s running around inside of all of these objects, no need to throw another one in there if not absolutely necessary. But it’s really just a matter of personal preference there 🙂

Hopefully this has cleared up some of the weirdness in uses of different this syntaxes.