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.

  • wonderful and useful examples
    thx
    Mani

  • Thanks. Really really useful.

  • matthew

    great great great thanks!

  • Ken

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

  • Son

    yahooooooooooooooooooooooooooooooooooooooooo !! Perfect, thank you so much.

  • staras

    Perfect. Perfect. Perfect. Thanks a lot.

  • sohelelite

    Dream comes true

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

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

  • Isaac Gateno

    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

      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

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

  • VietNV

    Thank Mr Coenraets. This sample’s very helpful.

  • Rob

    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

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

  • Eugene

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

  • geo

    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

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

      • DashMug

        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.

        • And comment / delete the line ” ” and all good,
          but when you save a record mark error “An error occurred while trying to delete this item” as I fix the actuliazar and eliminated if work.

        • already comment / delete the line “src = js / memorystore.js ” and all good,
          but when you save a record mark error “An error occurred while trying to delete this item” as I fix the actuliazar and eliminated if work

  • fred

    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;
    }
    });

    • And comment / delete the line “src = js / memorystore.js ” and all good,
      but when you save a record mark error “An error occurred while trying to delete this item” as I fix the actuliazar and eliminated if work

  • miguel

    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

  • Default User

    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

  • Pingback: NodeCellar: Sample Application with Backbone.js, Twitter Bootstrap, Node.js, Express, and MongoDB()

  • mj

    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

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

  • Herry

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

  • very blog good

  • ketan

    Great!

    I was looking such tutorial for long time.

    thanks for sharing. keep it up.

    • ketan

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

  • Pingback: My adventures in front-end-land | Stefan Norberg's weblog()

  • Pingback: Commavee » Using Node.js, Express, Socket.io and Exec()

  • Janka
  • Frank

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

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

  • 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?

  • shahin

    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

  • e_char

    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?

  • 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?

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

  • Orion

    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

  • 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

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

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

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

  • Pingback: node.js socket.io express live page view counter for each page currently accessed on 1 instance | Technology & Programming()

  • Ursula

    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.

  • 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

  • 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!

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

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

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

  • 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

  • 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).

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

  • thano you admin

  • Mohamed Jubair

    Thanks and it is really useful

    Single Page Applications Development

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

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

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

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

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

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

  • kiran

    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.

  • 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!

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

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

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

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

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

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

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

  • 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!

  • 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!

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

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

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

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

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

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

  • your web thanks

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

  • Pingback: Video Marketing Ideas That Will Help You Out! » Blog Archive » Best Download Video App()

  • Leo

    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?

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

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

  • it’s greate thank’s

  • k balu

    Very nice article, can you able to add search and sorting facility in it?…

  • wow, it’s very cool.. arigatou..

  • That is very good comment you shared.Thank you so much that for you shared those things with us.Im wishing you to carry on with ur achivments.All the best.

  • Are there any restrictions as to where to put this script on a web server?
    I have it installed in a WebIDE workspace sub folder and I think this may be causing the routing not to work so the app can not connect to the db.

    I have done on the set up steps for the php api
    Checked permissions/groups on server
    Verified mysql db is working and accessible from other apps on the same server

    http://on-line-interactivity.com/WebIDE/workspace/WineCellerApplication/ccoenraets-backbone-cellar-f465481/bootstrap/index.html

    Anyone else having this type of issue?

  • This site post is excellent, probably because of how well the subject was developed. I like some of the comments too though I could prefer we all stay on the subject in order add value to the subject!

  • Pingback: Liste 1 | Arif Kibrit()

  • Formalarımızda kullandığımız kumaş; birinci sınıf mikro-interlok olup; esnek-fit, anti-bakteriyel, termo-balans ve hemen kuruma özelliğine sahiptir. Futbol maçlarınızda size hareket özgürlüğü sunan bu formalar; günlük olarak giyilebilecek kadar şık tasarlanmıştır. Forma Modellerimiz özel dikim ve Dijital baskılı olarak iki tür üretilmektedir.
    Firmamızın en fazla üretim yaptığı, spor çoraplarında kullandığımız ürünler: pamuk ,koton, polyester, naylon ve likradır. Anti-bakteriyel içermektedir.

  • happy new years

  • Pingback: Single Page App – Tìm hiểu backbone.js | QuyềnVịnhXuân()

  • thanks boss

css.php