TemplateManager

I love Backbone.js. But it’s not perfect. One of my main problems with it is inline templates. Inline templates are templates that are contained within script tags within an HTML document. Almost every Backbone.js tutorial I’ve seen uses inline templates. But in the real world, this is a horrible way to build your web app.

Yet, it seems no one ever talks about this important piece of building real world web apps. There are some notable exceptions however. Angular.js lets you use external templates. Require.js has a plugin which lets you load templates as external dependencies, and many Backbone.js developers use and recommend this method. But, my opinion is that you shouldn’t be forced to use the entire Require.js library just for one feature.

That’s why I created a small script called TemplateManager. TemplateManager uses jQuery to asynchronously fetch and cache external template files. It also uses Underscore.js to pass the rendered template to a callback. And it uses Promises, actually jQuery’s Deferreds, to handle callbacks.

I like it because you can preload all your templates on initialization and because they are cached you can use them on demand later when you render your views. By preloading them, the requests happen in the background asynchronously so nothing is potentially blocked except whatever is rendered initially. You can also lazy load them and only fetch them when the view is created and rendered.

jQuery and Underscore are required for this, but Backbone is not. This allows you to use it with any application, although it works really well with Backbone since jQuery and Underscore are dependencies. I could have made it a Backbone plugin, but since it’s not a dependency, it can be used anywhere so I didn’t want to force that. I think in the future it would be useful to add support for other templating libraries so Underscore wouldn’t be a dependency in that case.

Check it out in the wizard-mvc project or on GitHub.

Marionette.TemplateManager

I also created a version of this for Marionette.js called Marionette.TemplateManager which is a Marionette plugin. I’ve been trying out Marionette recently, and I thought it would be nice to utilize this here too. One thing about Marionette is that it already has a TemplateCache object that caches inline templates internally. Marionette.TemplateManager takes advantage of this by using the TemplateCache instead of its own internal cache. It doesn’t return the compiled template with the promise however since Marionette also handles that internally. With Marionette, you can also change the default templating library so you don’t have to use Underscore templates.

Check it out in the wizard-mvc project or on GitHub.

Use setTimeout with QUnit and Sinon.js

I am currently using QUnit with Sinon.js in my JavaScript testing setup. However, I ran into a problem attempting to use setTimeout with QUnit along when using Sinon.js. Here is what I found.

QUnit advises using setTimeout when testing asynchronous functionality. But, I found that this did not work when you include Sinon.js. The reason is that Sinon.js provides fake timers and in doing this it overrides the setTimeout method. If you need to use setTimeout, you must change the config in Sinon.js.

sinon.config = {
    useFakeTimers: false
 };

Changing the config above will allow you to use setTimeout with Sinon.js. This isn’t very clear in the documentation unfortunately.

Underscore 1.5 Released

Underscore 1.5 was just released two days ago. The last significant update prior to that was 1.4.4 released on January 30th, 2013. The biggest feature was the unzip method which has now been pulled out of Underscore in the 1.5.1 release today. Underscore is a utility-belt library for JavaScript and also a dependency of Backbone.js.

It seems humorous to pull the biggest feature in a 1.x release 2 days after releasing it. Perhaps creator Jeremy Ashkenas thought so, calling the commit, “remove silly duplicate unzip function. Favor _.zip.apply in the docs.” You can read the discussion and the reason for this change here on GitHub.

Now that the unzip method has been pulled there aren’t many significant changes which makes the 1.x release number seem kind of silly. Maybe the source map, plus the number of changes warrant it. Anyway, here’s the changelog which you can also see in the docs.

  • Added a new unzip function, as the inverse of _.zip.
  • The throttle function now takes an options argument, allowing you to disable execution of the throttled function on either the leading or trailing edge.
  • A source map is now supplied for easier debugging of the minified production build of Underscore.
  • The defaults function now only overrides undefined values, not null ones.
  • Removed the ability to call _.bindAll with no method name arguments. It’s pretty much always wiser to white-list the names of the methods you’d like to bind.
  • Removed the ability to call _.after with an invocation count of zero. The minimum number of calls is (naturally) now 1.

Unit Testing Ajax with Sinon.js and QUnit

I’ve done unit testing with JavaScript using QUnit, but I’ve never tried writing unit tests for Ajax. I recently learned about Sinon.js however, and that has taken unit testing in JavaScript to a whole new level for me. By default, Sinon.js doesn’t work with QUnit, but fortunately you can add another script to make it work.

While attempting to write unit tests for Ajax, I had trouble finding good information. I actually found the solution in the Sinon.js docs. The secret to unit testing Ajax is not spies, stubs or mocks that are available in Sinon.js but the Fake XMLHttpRequest. This allows you to test Ajax calls and callbacks without making actual Ajax requests. The following test passes in QUnit.

test("ajax tests", function () {
    var xhr = sinon.useFakeXMLHttpRequest();
    var requests = sinon.requests = [];

    xhr.onCreate = function (request) {
        requests.push(request);
    };

    var callback = sinon.spy();

    $.ajax('/some/article', { success: callback });

    equal(sinon.requests.length, 1);
    equal(sinon.requests[0].url, "/some/article");

    requests[0].respond(200, { "Content-Type": "application/json" }, 
'[]');

    ok(callback.called);
});

You can see the code working here in jsfiddle. As you can see, the Ajax request was called with the right url. With the respond method, we were able to make our fake Ajax call return a 200 code so that the callback will be run as well. The trick is calling the respond method every time a request is sent. You just have to increment the number of the array item.

Here I am only returning an empty array because I couldn’t get the code to work in jsfiddle, but you can control what data is returned by the Ajax call, as well.

That’s it. I didn’t go into detail here about how QUnit or Sinon.js work, so you will need to check out their respective documentation if you are wondering about that. Unit testing Ajax is just one of the benefits of Sinon.js. If you aren’t already using it, I recommend that you do.

WordPress Users Plugin Moving to GitHub

I am still not planning on continuing development on the WordPress Users plugin. However, rather than kill it entirely or let it linger in the WordPress Plugin repository, I thought that it might be better served to move the codebase to GitHub. I hope that putting the project on GitHub will bring more visibility to it so that others may be encouraged to contribute to the development of the plugin.

Make sure to get the latest version from GitHub instead of the official WordPress Plugin site. If you are using it and have a problem or a question, please create an issue there. If you want to contribute, please submit a pull request. I will try to help out where I can so that others my still find it useful.

Managing Front-end Dependencies with Bower

I recently wrote 2 posts on setting up webapps with Yeoman and generators. In part of the first tutorial, I showed how Yeoman manages front-end dependencies with Bower. In this post, I will expand on Bower and how you can use it to manage dependencies in your apps.

Bower requires Node.js and can be installed via npm.

npm install -g bower

Bower is a command line tool, and the easiest way to figure out what you can do with it is get a list of commands by typing bower help. You can then get more details on a specific command by typing bower help <command> where <command> is the name of the command you want to use.

bower help
bower help <command>

You can then search for packages you want to install by name. Searching in Bower will give you a list of packages to choose from.

bower search <name>

When you want to install a package, simply type bower install <pkg> where <pkg> is the name of the package. This will install the package locally in a directory in your webapp. By default, Bower uses a directory called bower_components where the packages are installed. Bower also keeps a list of which packages are installed in a file called bower.json. However, this does not get automatically updated when you install a package. You can do that by typing bower install <pkg> --save.

bower install <pkg>
bower install <pkg> --save

You can also update packages easily  by using bower update <package>. Or you can update all installed packages at once with bower update, although it only updates packages listed in bower.json.

bower update
bower update <package>

This information should be more than enough to get you pretty familiar with using Bower to manage dependencies in your projects. Here is a list of additional commands which you may find helpful.

info - version info and a description of a package
init - automatically create a bower.json file
list - list all installed packages
uninstall - uninstall a package

While using a tool like Bower can make dependency management easy, there are a few drawbacks. Bower uses Github as a package registry. By using official repos rather than relying on someone to update the directory with new packages, Github with its massive user base takes care of that for you. However, this means that when you install a ‘package’ from Github, everything in the Github repository is installed as part of the package. While using Github maximizes the number of packages available and ensures that they will stay somewhat up to date, it’s not appealing at all to install everything in the Github repo when you may only need 1 or 2 files at most.

Another drawback is versioning. I’ve not yet found a good way to version dependencies that Bower installs. For example, when you install jQuery using Bower, the file is named jquery.js in a directory named jquery. The only way to know which version you have is to view the source. So if you wanted to rollback at some point, you would have to use version control which is not as easy as being able to switch between files.

Having a package manager for the web is a great idea, and Bower is the best implementation that I’ve seen so far. It doesn’t hurt that it works so nicely with Yeoman, but it also works just as nicely in any project. As I noted in my other post, it can be especially helpful in setting up demo projects and sample apps. Give it a try and see if Bower can help you in your projects.

Setting up a Backbone.js Webapp with Yeoman, Grunt and Bower – Part 2

This is part 2 on how to set up a Backbone.js webapp with Yeoman, Grunt and Bower. You can find part 1 here. In part 2, I will discuss using generators to set up your Backbone app.

As I mentioned in part 1, there are 2 officially maintained generators for Backbone, Backbone.js generator and Backbone Boilerplate generator. I will quickly walk through what you get when using either one.

To use Backbone.js generator, first you install the package via npm. Then, create a new directory for your app and run the yo command while in the new directory.

npm install -g generator-backbone
yo backbone

This generator uses Bower to install its components including jquery, backbone, modernizr and underscore. Bootstrap for Sass can also be installed when prompted. It also updates your bower.json file for you. The other thing it does is add some boilerplate code to main.js, which is very minimal. It’s very similar to doing it the way that I did in part 1, except it saves you the steps of downloading backbone and underscore, updating bower.json and adding them to your index.html file.

The second example, Backbone Boilerplate generator, goes further than the previous one, using Backbone Boilerplate and require.js for the boilerplate code. To use this, first you install the package via npm. Then, create a new directory for your app and run the yo command while in the new directory.

npm install -g generator-bbb
yo bbb

This installs backbone, jquery and lodash (an underscore alternative) for you, among others, but does not use Bower to manage components. It also installs a lot of boilerplate code which is found in app.js, main.js and router.js. If you like require.js and plan on using it, then great. If not, then you would have to delete those files as well as the boilerplate code which uses it.

Personally, I prefer Backbone.js generator due to the fact that it uses Bower to install components, is much less opinionated on how you set up the app and doesn’t care if you use require.js or not. If you already plan on using Backbone Boilerplate and require.js, then you will probably prefer the Backbone Boilerplate generator.

Setting up a Backbone.js Webapp with Yeoman, Grunt and Bower

A lot of things have changed in the JavaScript developer’s workflow over the past year. There are some new tools out there that make things a lot easier, so I thought I would dust off the old blog and do a write up on one of these tools called Yeoman.

Yeoman is “a robust and opinionated client-side stack, comprising tools and frameworks that can help developers quickly build beautiful web applications”. I find that not only is Yeoman awesome for helping you build webapps, it is a great way to build mock applications as well.

Yeoman requires node.js and can be installed via npm. You can find the installation details in the documentation, not to mention the homepage, so I won’t go into that here. Installing Yeoman gives you a set of tools which will give you the ability to scaffold out a new web application, build, preview and test your project, and easily manage dependencies.

To set up a new webapp with Yeoman, I make sure I have the latest version of node.js by going to the homepage and getting the most recent install package. I then make sure all the npm packages I have installed are up to date by running the update command: npm update -g. The -g tells npm to update all the globally installed packages. This is a good time to mention all the tools mentioned in this article are command line. If you are a developer or an aspiring one, I suggest getting as familiar with command line as much as possible, if you aren’t already.

I create a new directory for the app called webapp and cd into the new directory. To scaffold out a new webapp with Yeoman, run the command yo webapp. This actually uses a Yeoman generator called generator-webapp to install the webapp scaffolding in addition to Bower dependencies, npm dependencies and Grunt tasks. If you don’t have the webapp generator installed, you can install it by running npm install -g generator-webapp. Once you answer a few set up questions you are ready to go. Bootstrap from Twitter is a good way to easily scaffold webapps, so I always let Yeoman install that as well.

If I look in the bower_components folder of my new app, I can see that Yeoman installed jQuery, Modernizr and Bootstrap already. I want to use Backbone.js in my new webapp as well. Yeoman makes it easy to manage these dependencies and install new ones via Bower. To install Backbone.js with Bower, simply run the command bower install backbone --save. The --save on the end automatically updates the bower.json file. This file shows you what dependencies have been installed in your app via Bower. You should be aware that Underscore.js is a dependency of Backbone, so we can install that via Bower as well by running bower install underscore --save.

That’s it! Once you have everything in place, you can test your new app with Grunt by running grunt server. Just make sure that you include your new dependencies in your app so that they are available. If you want them to be minified via the build tasks available with Grunt, you need to include them inside the special build comments.

If you want to go further with Backbone.js in Yeoman, there are 2 officially maintained generators for Backbone. One is generator-backbone and the other one is called generator-bbb and uses Backbone Boilerplate.

Here is a recap of all the commands I used above to set up my new webapp.

npm update -g
cd webapp
npm install -g generator-webapp
yo webapp
grunt server
bower install backbone --save
bower install underscore --save