Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

Using Underscore.js


Underscore.js (http://underscorejs.org/) is a powerful utility library that provides a lot of functional programming support for your JavaScript code. In general, JavaScript comes up with a very low number of utility methods on its own, and most of the time we need to either develop our own functions or depend on another library for these methods. Underscore comes up with a bagful of highly efficient utility methods, which makes it an excellent tool for your JavaScript projects. The functions it provides can be grouped into the following sections:

  • Collections (Array or Object)

  • Arrays

  • Functions

  • Objects

  • Utility

  • Chaining

These include functions for iterations, sorting, filtering, conversions, templating, comparisons, scope binding, and many more. The main benefits of using this small library are as follows:

  • It helps you to make the JavaScript code more intuitive and concise.

  • In addition to the convenient methods, Underscore also implements cross-browser versions of newer JavaScript functions, which are only available in modern browsers. Underscore will detect whether the browser supports the method, and will use the native implementation if it is present. This boosts the function's performance to a great extent.

  • The minified and gzipped version of the library weighs only 4.9 KB, which leaves little excuse for not taking advantages of this library.

  • The library is completely DOM-free—so you can use it for your server-side JavaScript code as well.

  • Excellent documentation similar to Backbone.js with examples is available at http://underscorejs.org/.

Backbone.js has a hard dependency on Underscore.js, and you are bound to use it if you are developing your applications with Backbone.js. However, even when you are not using Backbone, we encourage you to use Underscore.js for your JavaScript projects. It adds no overhead, integrates easily, and makes your code more robust even when you are not aware of all the underlying engineering principles employed by this library.

There is another library named Lo-dash (http://lodash.com), which provides an Underscore built to perform drop-in replacement of the Underscore.js library. It is said to have a slightly better performance than Underscore.js. You can try either of them to achieve the same result.