Share Tweet Reccomend

Backbone.js Views

In the following segment, we are gong to look at views in Backbone.js.

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

What is a View?

As the name suggests, a “view” has to do with something you “view” on your screen (wow, what a concept!) :). But if you have done any programming in other languages before and you’re familiar with the Model View Controller software design pattern, the same pattern that Backbone.js follows (albeit very roughly), sometimes you have to take a moment to think about what is being referred to when talking about a view. Often times when you think of a “view” in an application framework such as CodeIgniter, ASP.NET MVC, or Django you tend to think of an entire rendered page of output (at least I do). Yes there are things like “partial views” and other components of MVC that don’t necessarily mean that a view is an entire rendered page, but that is just the tendency that I gravitate towards. When you are returning a view in frameworks such as those, you are often doing so in response to a browser’s request and routing them to a particular web page.

Read More »

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

Creating a Facebook “Like” Box in WordPress

In what follows, we’re going to take a look at how to create a Facebook Like Box in WordPress. If you create a Facebook Like box on the Facebook developer’s page, Facebook will give you some code to paste into your website. Something like the following…

<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&width=292&height=590&show_faces=true&colorscheme=light&stream=true&border_color&header=true" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:590px;" allowTransparency="true"></iframe>

This is an example of the iframe generated code, though there are a number of different types of code they’ll give you to choose from (HTML5, XFBML, etc).

You could certainly take the approach to paste this code directly into the PHP files in your WordPress theme where you want to show your Facebook Like box, but we’re going to do this in the form of a WordPress shortcode. That way we can pass in variable content to our Facebook Like box and we don’t have to update the raw code anytime we want to make a change.

Create a function in the location in your theme where you normally register your shortcodes. A lot of times this is the functions.php file but in the author’s humble opinion I believe that there are ways to keep your code more organized. Whether you are using functions.php or a class, add the following function to your code wherever it seems good to you…

function facebookBoxShortcode($atts, $content = null) 
{
	extract(shortcode_atts(array("id" => '', "path" => '', "showfaces" => 'true', "colorscheme" => 'light', "bordercolor" => 'white'), $atts));
	$scheme = '';
	$faces = '';
	if ($colorscheme == "dark")
		$scheme = "dark";
	else 
		$scheme = "light";
	if ($showfaces == "false")
		$faces = "false";
	else 
		$faces = "true";	
	return '<iframe id="'.$id.'" class="facebookBox" src="//www.facebook.com/plugins/likebox.php?href='.$path.'&colorscheme='.$scheme.'&show_faces='.$faces.'&border_color='.$bordercolor.'&stream=false&header=false" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowTransparency="true"></iframe>';
} 

Then immediately after this you’ll want to register your shortcode…

add_shortcode('facebookbox', 'facebookBoxShortcode');	

If you are registering your shortcode in a class — which I think is a good idea — then you’d use the following slightly different code instead…

add_shortcode('facebookbox', array($this, 'facebookBoxShortcode'));	

What we are doing in our function is allowing for a number of different variables to be passed into our shortcode.

  • id: This is where we can set the “name” of your Facebook box. It is used as an identifier if you want to have multiple different Facebook boxes on the same page. It can have any single word string value but each should be unique because (as you can see in the code), it maps to a CSS ID selector.
  • path: This where you’d want to se the URL of the Facebook page you want people to “Like”. The default we have set is http://www.facebook.com/platform, but you’d want to change this to your own page.
  • colorscheme: This setting could have the string value of either “dark” or “light”
  • showfaces:
  • bordercolor: Set the color of the border here. The default value is “white.”

We are now all set. Once you have your variables all configured the way that you want them, to use our newly implemented shortcode you could just add the following to your page or post…

[facebookbox id="myFacebookBox" path="http://www.facebook.com/yourpage here" showfaces="true" colorscheme="light" bordercolor="white"]

If you wanted to use this code outside of the WordPress Loop, such as your sidebar.php or footer.php files, you could use the following….

echo do_shortcode(‘[facebookbox id="myFacebookBox" path="http://www.facebook.com/yourpage here" showfaces="true" colorscheme="light" bordercolor="white"]‘);

May many Facebook “Likes” follow you wherever you go for all the days of your life.

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.