Single-Page CRUD Application with Backbone.js and Twitter Bootstrap

A few weeks weeks ago, I posted a first Backbone.js and Twitter Bootstrap sample application. While interesting, “Employee Directory” is a read-only application. As such, it doesn’t show off the full power of Backbone’s models or the coolness of some of Bootstrap’s data entry features such as forms, validation, etc.

To demonstrate these features, I decided to revisit my wine cellar application, which was in need of a serious UI makeover.

You can run the application here.



This online version uses an in-memory datastore: all your changes will be lost the next time you start the application or hit your browser’s refresh button. The image upload feature is also disabled, but you can still drag an image from your file system and drop it in the Wine Form, which is pretty cool (see the note about browser support below). The source code available on GitHub includes a persistent back-end (in addition to the in-memory datastore), and a fully functional implementation of the file upload feature.

Code Highlights

Template Loader

This application features a template loader that now uses jQuery “deferreds” to load the HTML templates more efficiently.

Drag-and-Drop File Upload and HTML 5 File API

To upload an image file for a Wine, drag a file from your file system and drop it in the image box inside the Wine Form: The image is automatically displayed inside the img tag. This is done using the HTML 5 File API and doesn’t require a server roundtrip.

NOTE: This feature only works in Chrome at this time. I will implement an alternative implementation in a future version of the application to provide a consistent behavior across browsers.

The image is uploaded to the server using Ajax (XHR) when you save the form: no page refresh or iframe hack.

Paging

Twitter Bootstrap provides easy markup and styles to create paginated lists. In this application, the Bootstrap markup and styles are “componentized” or “widgetized” into a Backbone View (Paginator), which adds the appropriate pagination behavior.

NOTE: In the current implementation of this application, the entire data set is always retrieved from the server and paging is provided for a cosmetic/layout reason. You could easily replace this implementation with a true paging strategy where pages are lazy-loaded from the server as needed.

Forms

Backbone Cellar also uses Twitter Bootstrap’s forms, which greatly help with form layouts (see WineView).

Validation

Twitter Bootstrap also provides simple markup and styles to highlight validation errors in forms. In Backbone Cellar, Bootstrap’s validation markup and styles are wired with validation rules defined in the Backbone model. Note that at this time, the application doesn’t use the Backbone model’s default validate() method, but custom validateItem() and validateAll() methods instead.

The application also uses other Twitter Bootstrap features including thumbnails, dropdowns, alerts, etc.

Source Code

The source code is available in the bootstrap folder of the backbone-cellar repository on GitHub.

Disclaimer

This is a sample application, not a production application. Some trade-offs were made to keep the code generic, simple and readable. In a real-life application, you should consider implementing a namespacing scheme to keep the global namespace clean, and other optimization techniques such as view and/or data caching.

60 Responses to Single-Page CRUD Application with Backbone.js and Twitter Bootstrap

  1. Manigandan K May 4, 2012 at 10:14 am #

    wonderful and useful examples
    thx
    Mani

  2. Thanish May 4, 2012 at 4:11 pm #

    Thanks. Really really useful.

  3. matthew May 8, 2012 at 4:12 am #

    great great great thanks!

  4. Ken May 11, 2012 at 8:45 am #

    Great work! A quick note: the content is obscured by the header on an iPad.

  5. Son May 11, 2012 at 9:33 am #

    yahooooooooooooooooooooooooooooooooooooooooo !! Perfect, thank you so much.

  6. staras May 11, 2012 at 1:26 pm #

    Perfect. Perfect. Perfect. Thanks a lot.

  7. sohelelite May 13, 2012 at 7:08 pm #

    Dream comes true

  8. skusunam May 14, 2012 at 5:08 pm #

    As usual all posts from you are very helpful. Just picked up Backbone.js 1hr back and i already know everything about it. Thank You.

  9. Frank Bølviken May 14, 2012 at 7:12 pm #

    Hi. Have you implemented modal windows with backbone.js yet? I can’t seem to get it working.
    Other than that, great example!

  10. Isaac Gateno May 14, 2012 at 7:29 pm #

    What webserver are you using? I’m trying to run a similar app using lighttpd on ubuntu but I can’t seem to figure out how to configure lighttpd to work properly with Slim in a subdirectory. Any insights?

    Thanks for the tutorial by the way. It’s very helpful.

    • gregorysamsa May 19, 2012 at 1:48 am #

      You’ll have to set up virtual host in lighttpd.conf

      assuming you’ve created cellar folder in lighttpd/cellar/

      $HTTP["host"] =~ “cellar” {
      server.document-root = “/home/lighttpd/cellar/http”
      }
      For localhost.cellar or cellar.localhost

      $HTTP["host"] =~ “(^|\.)cellar\.localhost$” {
      server.document-root = “/home/lighttpd/cellar/http”
      }

      • gregorysamsa May 19, 2012 at 1:53 am #

        Forgot to add that you need to have the api folder in root for this work and slim inside the folder.

  11. VietNV May 18, 2012 at 10:30 pm #

    Thank Mr Coenraets. This sample’s very helpful.

  12. Rob May 23, 2012 at 1:42 am #

    Great work Mr Coenraets.

    This is exactly the framework I was looking for when developing my proof of concept. There is one issue I can’t get around though. I can’t connect to mysql to pull records from. I have rechecked my api/index.php several times but still no luck. I removed .

    To use the app with a persistent RESTful back-end (provided in the GitHub repo), simply comment out the line below.

    Do I need to implement anything else???
    Any suggestions as I’m running out of ideas.

    Thanks

  13. Thomas Deutsch June 1, 2012 at 1:48 pm #

    Great Tutorial, Thank you!
    I have found 2 small things:

    1. The tagName for the WineListItemView is set to ‘li. But your template for the items also contains the so that you end up with two for every element.
    2. The code in the description is not the same as the code in the example.
    in the example i found the el: $(‘#wineList’) – not in the description.

  14. Eugene June 29, 2012 at 1:23 pm #

    Thanks for the great tutorial, however this works with 1 model only. It would be greate if you could make a tutorial on how to use nested views (when top view switches pages and nested view displays the items).

  15. geo July 1, 2012 at 11:00 pm #

    Hi Christophe

    Great App!

    I Have one question:
    Why when I try to add a wine the framework said: “Success! Wine saved successfully”. However when I check my database on wine don’t appear the new resource.

    Thanks!!

    • DashMug September 20, 2012 at 9:25 pm #

      I believed you forgot to uncomment the “” line in index.html.

      • DashMug September 20, 2012 at 9:26 pm #

        I forgot to remove the script tags. What I meant to say was you did not uncomment the line where “script src=”js/memorystore.js” can be found.

  16. fred July 3, 2012 at 1:04 pm #

    Hi
    I’m a beginner so I read your post with great interest. About the paginator, I think it would be more interesting for performance to create a variable with a list of pages to be displayed and then injecting it into the DOM. Something like:

    window.Paginator = Backbone.View.extend({
    className: “pagination pagination-centered”,
    initialize:function () {
    this.model.bind(“reset”, this.render, this);
    this.render();
    },
    render:function () {
    var items = this.model.models;
    var len = items.length;
    var pageCount = Math.ceil(len / 8);
    $(this.el).html(”);
    var pages = ”;
    for (var i=0; i < pageCount; i++) {
    pages += "” + (i+1) + ““;
    };
    $(‘ul’, this.el).append(pages);
    return this;
    }
    });

  17. miguel July 15, 2012 at 1:47 am #

    thanks for such amazing tutorials!
    i am a beginer with Bootstrap and I am having the following issue:
    -the nav bar won’t show in the browser :(
    what could be the problem? when running the app in Dreamweaver I can see all of it!
    thanks again

  18. Default User July 18, 2012 at 12:05 pm #

    When I try to add new model to database using slim.php, it is showing “Error An error occurred while trying to add this item”. But when I am trying to fetch, update, delete its working good. Why it is showing error only on adding ?

    bootstrap/js/views/winedetails.js

  19. mj October 13, 2012 at 1:31 pm #

    Great tutorial and demo. I have learned backbone by following ur simple demos. I have forked this project to include require.js for AMD support.

    https://github.com/phillycoder/backbone-require-cellar

    Thanks

  20. Maanas Royy October 30, 2012 at 7:46 pm #

    Great Tutorial.
    I m able to get the pagination work. I have two problems which may be very silly.
    a) How do i make the pagination limited to only 5 pages. Say i got 100 pages. I show only the 2 previous and 2 next pages along with next, previous link.
    b) I find in Network Tab that on each page click collection is being reloaded. I want to avoid that. Just load the collection once and then show the result.

    Thanks once again.

  21. Herry November 6, 2012 at 10:33 pm #

    Great tutorial.
    I got problem when trying to change the picture. Tested with Chrome(win7)
    How to upload image file using the the framework.

  22. sohbet odalari December 21, 2012 at 12:08 am #

    very blog good

  23. ketan March 3, 2013 at 5:04 pm #

    Great!

    I was looking such tutorial for long time.

    thanks for sharing. keep it up.

    • ketan March 3, 2013 at 5:16 pm #

      There are many global variables which may be conflict which other library. I think it should be wrap it in single object.

  24. Frank April 13, 2013 at 1:05 pm #

    I tried running the project locally and the local datastore only loads in Safari, not Chrome or Firefox. Any ideas?

  25. web hosting May 16, 2013 at 8:33 am #

    It is really a good and useful piece of information. I’m satisfied that you simply shared this useful information with us. Please stay us informed like this. Thanks for sharing.

  26. web hosting May 16, 2013 at 8:34 am #

    fantastic problems altogether, you simply received a new reader. What would you recommend in regards to your submit that you simply simply produced some days in the past? Any certain?

  27. shahin May 17, 2013 at 11:49 am #

    good app
    i’m beginner and taking ur app as a starting point.
    questions. the drop in functionality doesnt work.
    and also how can i add a select drop down to the view.
    thanks

  28. e_char June 24, 2013 at 8:18 pm #

    Thanks for this tutorial.

    I am having trouble dragging an image when I want to add/edit a wine item and I am using the most up to date version of chrome… Is this an issue for anyone else, or am I missing something?

  29. Roy M J July 17, 2013 at 2:08 am #

    Is there any backbone.js way of implementing the file upload instead of using jquery-ajax file upload.. Also by using ajax, is there any particular drawback?

  30. Bike Race cheat August 4, 2013 at 9:39 pm #

    You could definitely see your enthusiasm in the article you write.
    The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. Always go after your heart.

  31. Orion August 14, 2013 at 9:56 pm #

    I love your articles on backbone. I’m slowly getting my head around backbone, but i’m stuggling adding a next a previous function…

    Any idea how this could work?

    Maybe a future update? :)

    Ever way, thanks for sharing.

    Regards,
    Orion

  32. cheats for Marvel: Avengers Alliance August 20, 2013 at 8:55 pm #

    Great beat ! I would like to apprentice while you amend your web site, how can i subscribe for a blog site?
    The account helped me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided bright clear idea

  33. dialog:close September 15, 2013 at 8:36 am #

    My family members every time say that I am killing my time here at net, except I know I am
    getting knowledge daily by reading such nice articles.

  34. 0898jiaxiao.com October 18, 2013 at 2:56 am #

    of course like your web-site however you need to test the spelling on quite a few of your posts.
    A number of them are rife with spelling problems and I to
    find it very troublesome to inform the truth nevertheless
    I’ll certainly come back again.

  35. demirdöküm kombi servisi November 6, 2013 at 7:04 am #

    Really nice App. Thank you. I am a beginner and it will help to start learning backbone and Bootstrap. I have some ideas I will try to learn and do my webapp on my own. I am wondering why you didn’t commercialize this. Small companies can buy this right and is very useful for them just like any time tracking app.

  36. Ursula January 3, 2014 at 2:37 am #

    I have been trying to make your app read another table in mysql db with different information (show other things besides wine). I have modified the defaults in the models.js file, index.php (some sql queries and db info), also the winelistview.html file so the names match my db columns. I just cant seem to find what else i need to change. i just get the top menu and a blank page.

    What am I missing? I am new to backbone btw and I have been learning it on the go with your app.

  37. klima servisi January 31, 2014 at 5:34 am #

    The app is great but there are two problems that I found.

    1: the contact link doesn’t get the focus when clicked.
    2: if I click one of the top menus, home or contact, the show me doesn’t work, I have to remove the # from url and click again.

    I’m gonna try that application with knockout.

    Thanks for you time Christophe

  38. klima servisi January 31, 2014 at 5:35 am #

    Great information. I’ve been searching a long time for something like this.
    I should start now learning the aplication with the tutorial and your “Backbone Directory”, i’m new…hahaha
    Thanks a million!

  39. vestel klima servisi January 31, 2014 at 5:37 am #

    Really nice App. Thank you. I am a beginner and it will help to start learning backbone and Bootstrap. I have some ideas I will try to learn and do my webapp on my own. I am wondering why you didn’t commercialize this. Small companies can buy this right and is very useful for them just like any time tracking app.

  40. demirdökümkombi servisi January 31, 2014 at 5:38 am #

    Need small Info: Based on backbone+Bootstrap, are there any open srcd/example templates where a simple app that has support for user login/signups. I want to create an app that allows user to login and enter some details for app to work. One cant access others data. Any pointers how to go about ?? Any one else can also help me.

  41. baymak kombi servisi January 31, 2014 at 5:38 am #

    Looking forward to the mobile update and maybe some thoughts on how this Bootstrap approach compares to the one with jQuery Mobile?

  42. baymak kombi servisi January 31, 2014 at 5:39 am #

    I’d like to see your mojo source code. I have just put a mojolicious with bootstrap boilerplate on github and maybe we could complement it with some mojo with backbone boilerplate. Please feel free to contact me at tudorconstantin at gmail

  43. klimaservisi January 31, 2014 at 5:40 am #

    An extended version of this tutorial w/ additional login and admin capabilities.
    One of the biggest question to newcomers on rest-like architecture is how handling login and performance security operations (like adding or removing contents, auth, and so on).

  44. beko klima servisi January 31, 2014 at 5:40 am #

    I wonder how I can do to mount this tool locally (localhost). Right now I work, if not due to .htaccess is not set in my MAMP. Or is that the folder “api” PHP is not well located within the project and is not accessible.

  45. ortaköy çilingir February 23, 2014 at 8:12 am #

    thano you admin

  46. Mohamed Jubair March 27, 2014 at 1:25 am #

    Thanks and it is really useful

    Single Page Applications Development

  47. demirdöküm kombi servisi April 9, 2014 at 1:32 pm #

    I wonder how I can do to mount this tool locally (localhost)

  48. singer sewing machine agent in singapore April 17, 2014 at 2:20 am #

    They are mechanical sewing machine, electronic sewing
    machine, computerized sewing machine and overlocker sewing machines.
    Barcelona’s Puntada Group has developed a computer
    called the multi-head embroidery machine Thor series debut in the United States will not be smooth,
    may be due to mechanical problems which resulted in the cessation
    of sale. Whether you are on the beginner, intermediate, or
    advanced level the classes are available online.

  49. london property news April 19, 2014 at 10:58 pm #

    What that means in interest per month, I’m paying, just to get an idea.
    That doesn’t mean it’s not dangerous, that doesn’t mean
    it’s not bad – and london housing market this includes many tourists who are willing to buy 2, 400 for $25.
    What you can do things to affect this, but a top level data.

  50. best shoes for plantar fasciitis April 20, 2014 at 3:37 pm #

    Nice respond in return of this query with real arguments and explaining the whole thing concerning that.

Trackbacks/Pingbacks

  1. NodeCellar: Sample Application with Backbone.js, Twitter Bootstrap, Node.js, Express, and MongoDB - October 4, 2012

    [...] is a Node.js and MongoDB powered version of an application I initially posted here with PHP and Java backends. The original post provides some additional Backbone.js context. This [...]

  2. My adventures in front-end-land | Stefan Norberg's weblog - March 31, 2013

    [...] beyond the trivial hello world examples. I learned a lot from Christophe Coenraets blog post: http://coenraets.org/blog/2012/05/single-page-crud-application-with-backbone-js-and-twitter-bootstra… even though it’s very simple (in [...]

  3. Commavee » Using Node.js, Express, Socket.io and Exec - April 5, 2013

    [...] Inspiration for this example came partly from the fantastic demo application here by Christophe Coenraets. I’ve reused some of his structure & layout in this example. [...]

  4. node.js socket.io express live page view counter for each page currently accessed on 1 instance | Technology & Programming - November 10, 2013

    [...] using working code snippets from Christophe Coenraets and want to elaborate it into creating an array of msg.pageUrl to live view count each accessed [...]

Leave a Reply