Appendix C. Using jQuery UI with Backbone

 

One question I frequently am asked is how jQuery UI works with MVC frameworks like Backbone. This definitely is a topic worth discussing, because jQuery UI compliments Backbone quite nicely. The best way to use the libraries is to let Backbone do what it does best—manage an application’s data and views—and let jQuery UI do what it does best—the UI. Let’s look at how to do that.

Note

This guide is intended for readers who have some familiarly with the Backbone library, although I’ll try to provide enough context so that everyone can follow. To learn more about Backbone, you can refer to its documentation at http://backbonejs.org/, or Addy Osmani’s excellent (and free!) book on writing Backbone applications, available at http://addyosmani.github.io/backbone-fundamentals/.

C.1. Building a Backbone view

To show the integration in action, you’ll build a small sample app to manage a grocery list. Your grocery list will have a single piece of functionality: a button that removes individual groceries from the list. The HTML you’ll use to build this is shown here

<ul id="grocery-list"></ul>
<script type="text/template" id="grocery-template">
    <% _.each( groceries, function( grocery ) { %>
        <li>
            <%= grocery.name %>
            <button data-id="<%= grocery.id %>">Remove</button>
        </li>
    <% }); %>
</script>

and here’s the JavaScript you need:

Note

You can play with this example at http://jsfiddle.net/tj_vantoll/H3fHr/.

C.2. Adding jQuery UI to the view

C.3. Using declarative widgets