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.

86 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.

  51. Trina April 21, 2014 at 12:59 pm #

    Hi, I do think this is an excellent website. I stumbledupon it ;) I will return yet again since
    i have bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to help other people.

  52. Sung April 23, 2014 at 8:11 am #

    Greetings! Very helpful advice within this post! It is the little changes that will make the largest
    changes. Thanks for sharing!

  53. kiran April 24, 2014 at 6:53 am #

    Hi Christophe Coenraets,

    I have successfully created database and populated wine table. But i am not getting api/wines
    error showing is ” Failed to load resource: the server responded with a status of 404 (Not Found) ”
    “http://phpserver/trainee2014/Kiran/backbone/bootstrap/api/wines/”

    Please help.

  54. семенной April 24, 2014 at 2:32 pm #

    Hello there, I discovered your blog by the use of Google even as searching for a comparable
    topic, your site came up, it appears great. I’ve bookmarked it in my google bookmarks.

    Hello there, just changed into alert to your blog through Google, and found that it is really informative.
    I’m going to watch out for brussels. I will be grateful in the event you continue this in future.
    Many folks might be benefited from your writing. Cheers!

  55. gmail account creator April 26, 2014 at 9:21 am #

    If some one wishes expert view on the topic of
    blogging and site-building then i advise him/her to pay a visit this web site, Keep up the pleasant work.

  56. Go now April 28, 2014 at 4:52 am #

    Thanks to my father who informed me about this weblog, this web site is really awesome.

  57. coffee table plans April 30, 2014 at 3:49 am #

    Coffee table books are a popular and fun way for people to
    add a touch of class to their surroundings while showing off their
    own unique personalities. That fantasy wasn’t as distant as it seems like think.
    Glass coffee tables add a modern looks to the existing décor
    of your home.

  58. envoi de texto pas cher May 1, 2014 at 1:04 pm #

    Helloo I am so glad I found your blog, I really founbd you
    by error, while I was searching on Yahoo
    for something else, Anyways I amm hhere now and would just like to say cheers for a remarkable
    post and a all round exciting blog (I also love the theme/design), I don’t have time tto
    read through it all at the minute but I have saved it and alsdo included your RSS feeds, so when I have tike I will
    be back to read a great deal more, Please do keep up thee excellent job.

  59. http://calkiemsmacznezycie.blogspot.se May 2, 2014 at 1:47 am #

    axone    axons    ayahs    ayins    azans    azide    azido    azine.
    loutish  louvers  louvred  louvres  lovable  lovably  lovages  lovebug.
    mastered masterly masthead mastiche mastiffs mastitic mastitis mastixes.

  60. http://gregorygieg.Soup.io May 3, 2014 at 7:31 pm #

    Preventing mold growth in silicone mold tips other parts of the
    home requires containing the mold spores in
    the air. And they will all say, more or less, the same thing: clean the mold temporarily,
    but they are by no means ways to completely remove the mold problem.

    There are mold spores in the infected are must be cleaned as they are prime transports for mold
    spores.

  61. compost bin plans May 4, 2014 at 9:02 am #

    Many significant factors just for all of these some will probably
    more than likely upset category from this number.
    This is a great opportunity to engage students
    in writing in a science journal. To escape all this trouble
    and to save a lot of time and energy, a compost tumbler is your best option.

  62. www.youtube.com May 10, 2014 at 11:33 pm #

    you arre actually a good webmaster. The web site loading velocity is amazing.
    It kind of feels that you’re doing any unique trick.
    Furthermore, The contents are masterpiece. yyou have done a exccellent activity in
    this topic!

  63. film bokep May 14, 2014 at 12:07 am #

    Have you ever considered about including a little bit more than just your articles?
    I mean, what you say is important and everything. But imagine
    if you added some great graphics or video clips to give your
    posts more, “pop”! Your content is excellent but with images and clips, this blog could undeniably be one
    of the most beneficial in its niche. Awesome blog!

  64. the venus factor reviews May 20, 2014 at 1:04 am #

    Everyone loves it when people get together and share ideas.
    Great blog, continue the good work!

  65. buy t25 workout May 22, 2014 at 1:53 am #

    I lost 25 pounds watching calories with the help of the application. Oranj
    is a booming community based fitness, dance and yoga studio
    located on Lawrence Ave. As an individual steps into a kickboxing
    class they then have the power to let out all the anger and frustration that has been building up inside of them.
    It’s no secret that diets are big business, but many diet and calorie counting
    apps for your Black – Berry are free and really are handy to
    have.

  66. supple beverages May 22, 2014 at 9:21 am #

    Micro-organisms are present everywhere around us, in the air we breathe, in the food we eat, where we sleep, in the market place and even on the products that we casually pick up to inspect.
    Do you get into the daily grind fuelled by caffeine.

    Thinking about running has not solved many people’s fatness and fitness issues, so get into it and start a person’s running career today.

  67. Carole May 22, 2014 at 9:43 am #

    It is also healthy for your heart and lung function. Most of the people suffering from over
    weight and flabby tummy always opt for weight losing plans just to feel more confident.
    That is the one product I would recommend to anyone.

  68. tummystuffers.weebly.com May 24, 2014 at 4:03 am #

    Toys can be very powerful educational tools so don’t underestimate their power to teach.
    You can discuss some factual information or
    trivia about each one of them. You can take a look at the T-Star Games
    Store with a single click sitting alone.

  69. Great information. Lucky me I recently found your website by accident (stumbleupon).
    I have saved as a favorite for later!

  70. midea klima servisi June 13, 2014 at 2:43 pm #

    your web thanks

  71. Donte Bleattler June 21, 2014 at 12:45 am #

    I’m very pleased to discover this website. I need to to thank you for your time for this particularly fantastic read!! I definitely liked every bit of it and I have you saved to fav to see new information in your site.

  72. Leo July 3, 2014 at 2:59 am #

    Write more, thats all I have to say. Literally,
    it seems as though you relied on the video to make your point.
    You clearly know what youre talking about, why waste your intelligence on just posting videos to
    your blog when you could be giving us something informative
    to read?

  73. Valentin July 4, 2014 at 4:08 am #

    Your method of explaining all in this paragraph is in fact good, all can without difficulty understand it,
    Thanks a lot.

  74. pocket legends hack 3.5 July 6, 2014 at 10:52 am #

    Aquastations provide plastic cups and holders and regular sanitisations of
    your machine. Cruise vacations make it possible to pay one price and spend days to a
    week relaxing by the poolside. As a foundry, the
    Pou Chen Group of course is well versed in the principle of playing your own part,
    thus it has taken with international brand OEM win-win model.

  75. haqisaurus September 23, 2014 at 11:38 pm #

    it’s greate thank’s

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 [...]

  5. Video Marketing Ideas That Will Help You Out! » Blog Archive » Best Download Video App - June 28, 2014

    […] you have any issues regarding wherever and how to use youtube download mp3 , you can contact us at the web […]

Leave a Reply

css.php