Sample Mobile App with Backbone.js, PhoneGap, and a Local Database

In my previous post, I shared a simple Wine Cellar application built with Backbone.js and packaged as a mobile app with PhoneGap. That version of the application gets its data from a set of RESTful services, which means that you can only use it while online.

In this post, we explore an offline version of the same application: this new version gets its data from your device’s local database using the PhoneGap SQL database API.

By default, Backbone.js Models access their data using RESTful services defined by the Models “url” and “urlRoot” attributes. But Backbone.js also makes it easy and elegant to change your Models data access mechanism: All you have to do is override the Backbone.sync method. From the Backbone.js documentation:

Backbone.sync is the function that Backbone calls every time it attempts to read or save a model to the server. By default, it uses (jQuery/Zepto).ajax to make a RESTful JSON request. You can override it in order to use a different persistence strategy, such as WebSockets, XML transport, or Local Storage.

The documentation includes a useful example that shows how to replace the default Backbone.sync implementation with localStorage-based persistence where models are saved into JSON objects.

In our application, we will replace the default Backbone.sync implementation with SQL-based persistence using the device’s local database.

First, we create a data access object that encapsulates the logic to read (find), create, update, and delete wines. This simple application is read-only and only needs to retrieve collections. So, I only implemented the findAll() method and stubbed the other methods (find, create, update, destroy). WineDAO also has a “populate” function to populate the wine table with sample data.

window.WineDAO = function (db) {
    this.db = db;

_.extend(window.WineDAO.prototype, {

    findAll:function (callback) {
            function (tx) {
                var sql = "SELECT * FROM wine ORDER BY name";
                tx.executeSql(sql, [], function (tx, results) {
                    var len = results.rows.length;
                    var wines = [];
                    for (var i = 0; i < len; i++) {
                        wines[i] = results.rows.item(i);
            function (tx, error) {
                alert("Transaction Error: " + error);

    create:function (model, callback) {
//        TODO: Implement

    update:function (model, callback) {
//        TODO: Implement

    destroy:function (model, callback) {
//        TODO: Implement

    find:function (model, callback) {
//        TODO: Implement

//  Populate Wine table with sample data
    populate:function (callback) {
            function (tx) {
                console.log('Dropping WINE table');
                tx.executeSql('DROP TABLE IF EXISTS wine');
                var sql =
                    "CREATE TABLE IF NOT EXISTS wine ( " +
                        "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        "name VARCHAR(50), " +
                        "year VARCHAR(50), " +
                        "grapes VARCHAR(50), " +
                        "country VARCHAR(50), " +
                        "region VARCHAR(50), " +
                        "description TEXT, " +
                        "picture VARCHAR(200))";
                console.log('Creating WINE table');
                console.log('Inserting wines');
                tx.executeSql("INSERT INTO wine VALUES (1,'CHATEAU DE SAINT COSME','2009','Grenache / Syrah','France','Southern Rhone / Gigondas','The aromas of fruit and spice give one a hint of the light drinkability of this lovely wine, which makes an excellent complement to fish dishes.','saint_cosme.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (2,'LAN RIOJA CRIANZA','2006','Tempranillo','Spain','Rioja','A resurgence of interest in boutique vineyards has opened the door for this excellent foray into the dessert wine market. Light and bouncy, with a hint of black truffle, this wine will not fail to tickle the taste buds.','lan_rioja.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (3,'MARGERUM SYBARITE','2010','Sauvignon Blanc','USA','California Central Cosat','The cache of a fine Cabernet in ones wine cellar can now be replaced with a childishly playful wine bubbling over with tempting tastes of black cherry and licorice. This is a taste sure to transport you back in time.','margerum.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (4,'OWEN ROE \"EX UMBRIS\"','2009','Syrah','USA','Washington','A one-two punch of black pepper and jalapeno will send your senses reeling, as the orange essence snaps you back to reality. Do not miss this award-winning taste sensation.','ex_umbris.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (5,'REX HILL','2009','Pinot Noir','USA','Oregon','One cannot doubt that this will be the wine served at the Hollywood award shows, because it has undeniable star power. Be the first to catch the debut that everyone will be talking about tomorrow.','rex_hill.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (6,'VITICCIO CLASSICO RISERVA','2007','Sangiovese Merlot','Italy','Tuscany','Though soft and rounded in texture, the body of this wine is full and rich and oh-so-appealing. This delivery is even more impressive when one takes note of the tender tannins that leave the taste buds wholly satisfied.','viticcio.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (7,'CHATEAU LE DOYENNE','2005','Merlot','France','Bordeaux','Though dense and chewy, this wine does not overpower with its finely balanced depth and structure. It is a truly luxurious experience for the senses.','le_doyenne.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (8,'DOMAINE DU BOUSCAT','2009','Merlot','France','Bordeaux','The light golden color of this wine belies the bright flavor it holds. A true summer wine, it begs for a picnic lunch in a sun-soaked vineyard.','bouscat.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (9,'BLOCK NINE','2009','Pinot Noir','USA','California','With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.','block_nine.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (10,'DOMAINE SERENE','2007','Pinot Noir','USA','Oregon','Though subtle in its complexities, this wine is sure to please a wide range of enthusiasts. Notes of pomegranate will delight as the nutty finish completes the picture of a fine sipping experience.','domaine_serene.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (11,'BODEGA LURTON','2011','Pinot Gris','Argentina','Mendoza','Solid notes of black currant blended with a light citrus make this wine an easy pour for varied palates.','bodega_lurton.jpg')");
                tx.executeSql("INSERT INTO wine VALUES (12,'LES MORIZOTTES','2009','Chardonnay','France','Burgundy','Breaking the mold of the classics, this offering will surprise and undoubtedly get tongues wagging with the hints of coffee and tobacco in perfect alignment with more traditional notes. Breaking the mold of the classics, this offering will surprise and undoubtedly get tongues wagging with the hints of coffee and tobacco in perfect alignment with more traditional notes. Sure to please the late-night crowd with the slight jolt of adrenaline it brings.','morizottes.jpg')");
            function (tx, error) {
                alert('Transaction error ' + error);
            function (tx) {

I then added a “dao” attribute to the Models to specify which data object should be used to access their underlying data.

window.Wine = Backbone.Model.extend({
	urlRoot: "",
    dao: WineDAO

window.WineCollection = Backbone.Collection.extend({
	model: Wine,
	url: "",
    dao: WineDAO

NOTE: The application doesn’t need the url and urlRoot attributes anymore, but you can imagine a more sophisticated version of the app that would work with the RESTful services while online and fall back to the local database while offline.

With that infrastructure in place, we can now override Backbone.sync as follows:

Backbone.sync = function (method, model, options) {

    var dao = new model.dao(window.db);

    switch (method) {
        case "read":
            if (
                dao.find(model, function (data) {
                dao.findAll(function (data) {
        case "create":
            dao.create(model, function (data) {
        case "update":
            dao.update(model, function (data) {
        case "delete":
            dao.destroy(model, function (data) {


And finally, we need to open the database (and populate it with sample data) at startup:

window.startApp = function () {
    var self = this;
    window.db = window.openDatabase("WineCellar", "1.0", "WineCellar Demo DB", 200000);
    var wineDAO = new WineDAO(self.db);
    wineDAO.populate(function () {
        this.templateLoader.load(['wine-list', 'wine-details', 'wine-list-item'], function () {
   = new AppRouter();


I added this version of the application to the backbone-cellar GitHub repository here.

NOTE: You will have to create a PhoneGap project (see documentation here) or use the hosted build service to package the code as a native app for different mobile platforms.

  • Dustin Sullivan


    Great example here but have you attempted to run this on a mobile phone? I just tried in an emulator and android and the List does not scroll.

    • Benjamin

      Same here. Ran it on IOS, the list didn’t scroll as well. Are we missing something here?

  • Hey Christophe,
    It’s a nice example. I wonder why you are not using indexedDB in it as the W3C has officially “deprecated” Web SQL Database?

  • How to build group swf file single project thats run ipad any one help me

  • Calling all Technology Professionals

    Guys check this out….. If you have ideas on mobile apps for use on phones, submit ur apps a contest that gives you a chance to prove your mettle. Whether you are a professional developer or a student, every1 can submit their apps developed by using the Series 40 Web apps SDK and win.
    Register today to submit ur apps….

  • Really cool :)

    I plan to use this technique in my mobile apps soon.

  • Tyrone

    The github has a page not found error. please I would like to see the example.

    • Eduardo

      I also would like to see the example if possible.

      As this is my first comment, I would like also to congratulate you for this blog. Its helping me a lot with mobile development using phonegap, and to learn about Backbone.

  • Uri

    Correct URL to the backbone-cellar GitHub repository:

  • abayomi

    Hello christophe.Thank you for your blog and for taking out time to impact knowledge.However,I appreciate your employee directory with phone gap api for local storage-it has helped in my understanding of the subject.I came accross a problem recently cos I was trying to insert into my database in my local language with this text(Odò kan si ti Edeni ṣàn wá lati rin ọgbà na; lati ibẹ̀ li o gbé yà, o si di ipa ori mẹrin. ) but on display the result after select query gave was different(Odò kan si ti Edeni ṣà n wá lati rin á»gbà n…).Can you help.How do I get the exact text I inserted in the database.

  • It’s a nice example, thanks.

  • Have a fabulous time all of you lucky adequate to check out Russ tonight, he has been on best form this calendar year! his fanbase loves him far more tha ever!br /Almada powerful terms However you cannot really be taken seriously when you use CAN twice from the exact same sentence inside a context that isn’t going to make grammatical sense!

  • I used to be suggested this blog by my cousin. I’m no longer positive whether or not
    this submit is written by him as nobody else understand such detailed
    about my problem. You are amazing! Thank you!

  • Fantastic blog! Do you have any helpful hints for aspiring writers?
    I’m hoping to start my own site soon but I’m a little lost on everything.
    Would you suggest starting with a free platform like WordPress or
    go for a paid option? There are so many choices out
    there that I’m totally overwhelmed .. Any recommendations?
    Thank you!

  • Its so homey and family oriented that it feels like its straight out of “My Big Fat Greek Wedding. If you had to perform on America’s Got Talent, what would you do. The Seattle Waterfront, Kirkland, Edmonds, Everett – there are 24 restaurants in the Pacific Northwest.

  • An interesting discussion is worth comment. I believe that
    you should write more on this issue, it might not be a taboo subject but typically people do not discuss such subjects.
    To the next! Kind regards!!

  • The very core of your writing while sounding agreeable at first, did not really settle well with me personally after some time. Someplace throughout the paragraphs you actually managed to make me a believer but just for a short while. I still have got a problem with your jumps in assumptions and one would do well to fill in all those gaps. When you can accomplish that, I could certainly end up being amazed.

  • Excellent way of telling, and pleasant paragraph to take facts regarding my
    presentation topic, which i am going to deliver
    in academy.

  • Useful info. Forrtunate me I fouund уour site accidentally, aand І amm surprised
    why tuis coincudence ddid nott took lace earlier! І bookmasrked

  • Hay Day Hack Technique Download and install

    Hay-Working day by Supercell is liberated to get with the Appstore on your apple iphone
    or ipad tablet. I’d no challenges putting in together with the in genmeral activity was ansolutely free.
    I’ve also got no difficulties with fails or problems. The
    general activity necessitates 38.4mb off area. This program is upgraded for new
    iphone-5. In Use Acquisitions: the App cann be downloaded by You for free,
    but game currency can be bought by you for as little ass a few bucks on upp when you
    wish to urry things a little. Easily close thee overall performance reduced, when you decide
    upon not have to get drawn straight into choosing problemss
    annd return to it later on.With a bit of persistence the entire match is totally practical
    without having creating any acquisitions.

  • Very well written post. It will be supportive to anyone who employess it, including me. Keep up the good work – i will definitely read more posts.

  • celine luggage Handbags
    I’m really inspired with your writing skills and also with the layout for your weblog.
    Is that this a paid theme or did you modify it yourself?
    Anyway keep up the excellent high quality writing, it’s uncommon to peer a great weblog like
    this one these days..

  • Everyy weekend i used to pay a visit this site, as i wish for enjoyment, for the reason that
    this this website conations truly good funny material

  • Hello, i believe that i noticed you visited my blog
    thus i got here to go back the want?.I’m attempting to in finding things to enhance my
    site!I assume its good enough to make use of a few
    of your concepts!!

  • Hello. Just desired to consult a quick dilemma. I’m putting together my blog site
    in addition to want to realize where you still have your own topic?
    Ended up being the idea no cost? Or ended up being the
    item compensated? I can not apparently discover
    something just like this blog, and so with luck , you’ll
    be able to i want to understand. Thank you. PS, our apologies.
    The english language is just not my personal 1st words.

  • I absolutely love your blog and find a lot of your post’s to be
    just what I’m looking for. Do you offer guest writers to write content for
    you personally? I wouldn’t mind composing a post or elaborating on some of the subjects you write
    about here. Again, awesome blog!

  • I am extremely impressed with your writing skills as well as with
    the layout on your blog. Is this a paid theme or did you modify it yourself?
    Either way keep up the nice quality writing, it is rare
    to see a nice blog like this one today.

  • I visited many blogs however the audio quality for audio songs existing at this website is actually fabulous.

  • Asking questions are really nice thing if you are not understanding anything entirely, however this post gives good
    understanding yet.

  • This is just mind blowing ! Really liked it!

  • I enjoy what you guys are up too. Such clever work and reporting!
    Keep up the excellent works guys I’ve incorporated you guys to my blogroll.

  • Hello are usinng WordPress for your bllg platform? I’m new to
    thhe blog world but I’m trying to get started and create my own. Do you need any coding knowledge to
    make your own blog? Any help would bee greatly appreciated!

  • After looking at a number of the articles on your website, I honestly appreciate your technique of blogging. I saved as a favorite it to my bookmark website list and will be checking back in the near future. Please check out my web site too and tell me how you feel.

  • It’s remarkable to go to see this web site and reading the
    views of all friends concerning this article, while I am also zealous
    of getting know-how.

  • Thanks for another wonderful post. Where else
    could anybody get that kind of info in such an ideal
    method of writing? I’ve a presentation next week, and I’m on the search for such info.

  • Please let me know if you’re looking for a article author for your weblog.

    You have some really great posts and I believe I would be a good asset.
    If you ever want to take some of the load off, I’d love to write
    some material for your blog in exchange for a link back to mine.

    Please shoot me an e-mail if interested. Thank you!

  • Asking questions are actually fastidious thing if you
    are not understanding something completely, however this
    article offers nice understanding yet.

  • Classic, modern, vintage, luxurious, tasteful wedding invitations and (some)
    retro or art deco – all this can summarise
    without fault the Jewels and Lace collection.It features, as described, luxurious jewels and fine lace on a base of wonderful pearly
    card in ivory and white. From glittering sparkly crystals to shiny pearls and
    delicate luxurious laces, the Jewels and Lace collection has something on
    offer for every sophisticated bride who is after that traditional look with a twist.
    We like to call this the Wedding Dress of our Bohemian
    Dreams as each jewel, layer of lace and each cut of card are
    carefully selected and joined together to create that perfect classic wedding

  • The welfare of pets like dogs and cats is the primary concern of most pet owners as they
    treat them like their family members. This saves you the time and frustration of talking to
    a pharmacy tech on the phone. If you know how to use the Internet, ordering your own prescriptions can be as easy as turning on the
    computer while taking your morning coffee, and you never have to leave your home
    doing it.

  • Hi to all, how is everything, I think every one is getting more
    from this website, and your views are fastidious for
    new visitors.

  • I always used to study paragraph in news papers but now
    as I am a user of net therefore from now I am using net for content, thanks to web.

  • Remarkable! Its truly awesome piece of writing, I
    have got much clear idea concerning from this piece of writing.

  • An outstanding share! I’ve just forwarded this onto a colleague who was doing a little research on this. And he in fact ordered me lunch because I discovered it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanks for spending time to discuss this topic here on your internet site.

  • If some one desires expert view about running a blog afterward i advise him/her to visit this web site, Keep up the fastidious job.

  • This post is genuinely a fastidious one it assists new web people,
    who are wishing in favor of blogging.

  • Instead we suffer from it, by storing too much fat and rarely, if ever, burning
    it. When we try to muscle through with just conviction as our army we’re doing it the hard way.

    The author of this GFP article loves fruit and realises that this affair was fostered in childhood where his father
    grew many varieties of fruit trees in his home yard.

  • naturally like your web-site but you have to take a look at the spelling on several of your
    posts. A number of them are rife with spelling issues and I
    find it very troublesome to inform the truth on the other hand I will certainly come back again.

  • I don’t even understand how I stopped up here, but I assumed this post was great.
    I don’t realize who you are however certainly you are going to a
    famous blogger in case you are not already.

  • That is a great tip especially to those new to the blogosphere.
    Brief but very precise info… Appreciate your sharing this one.

    A must read post!

  • Those two restaurants have also experienced a decrease in sales, but Red Lobster’s sales declined
    the most. (203) 338-0808 A favorite Mexican restaurant of myriad local residents and visitors to the region, Coyote Flaco
    Restaurant regularly serves large portions of delicious
    Mexican food. These include chain restaurant locations and small,
    independently owned establishments.

  • Wow that was odd. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up.
    Grrrr… well I’m not writing all that over again. Anyway, just wanted to say excellent blog!

  • Wow, fantastic weblog format! How lengthy have you been blogging for?
    you made blogging glance easy. The whole glance of your site is
    great, let alone the content material!

  • SEO

    I’ve read some excellent stuff here. Definitely price bookmarking for revisiting.
    I surprise how so much attempt you set to create such
    a wonderful informative website.

  • Que post m

  • I am truly thankful to the owner of this web site who
    has shared this great post at at this time.

  • Everyone loves what you guys are usually up too. This sort of clever work and exposure!
    Keep up the great works guys I’ve included you guys to blogroll.

  • I like the valuable info you provide in your articles.

    I will bookmark your blog and check again here frequently.
    I’m quite certain I will learn lots of new stuff right here!
    Best of luck for the next!,

  • I’m not sure where you’re getting your info, but great topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for great information I was looking for this info for my mission.

  • WOW just what I was searching for. Came here by searching
    for OR

  • This is really interesting, You are a very skilled blogger.
    I have joined your feed and look forward to seeking more of your fantastic post.

    Also, I have shared your site in my social networks!

  • Wonderful goods from you, man. I’ve understand your stuff previous
    to and you’re just too fantastic. I really like what you’ve
    acquired here, really like what you’re saying and the way in which you
    say it. You make it enjoyable and you still take care of to keep it
    sensible. I cant wait to read far more from you. This
    is really a tremendous site.

  • seo

    whoah this blog is great i like studying your articles.
    Keep up the good work! You already know, many people are hunting around for this
    information, you can aid them greatly.

  • Have you ever thought about writing an ebook or guest authoring on other websites?

    I have a blog centered on the same subjects you discuss and would really like to have you share some stories/information. I know
    my audience would enjoy your work. If you are even remotely interested, feel
    free to shoot me an e mail.

  • Thanks for sharing your thoughts about หน้งโป็xxx.

  • There are however some will get his property by the unlicensed contractors rates and
    multiple strips, switches and other public agencies.
    I guess to answer visitors’ questions. They
    have the BBB? Congratulations to all tendering and selecting painters for a handbag hoarder named Adina to an article
    on contractor landscaping in DFW could be illegal immigrants.
    To learn more about his involvement with their work corrected.
    5 million in fines. A picture verifies the review of your home.

    But, unlicensed contractors wait up for your room or setting.

  • Does your website have a contact page? I’m having problems
    locating it but, I’d like to shoot you an email. I’ve got some suggestions for your blog you might be interested in hearing.
    Either way, great site and I look forward to seeing
    it develop over time.

  • Heplo there! Quick question that’s entirely off topic. Do you kniw how tto make your site mobile friendly?
    My website looks weird whenn browsing from my iphone.
    I’m trying too find a template or plugin that might be able to resolve this issue.
    If you havfe any suggestions, please share. With

  • Having read this I believed it was really enlightening. I appreciate you spending some time and effort to put this information together.
    I once again find myself spending way too much
    time both reading and commenting. But so what, it was still

  • Maurizio

    Hey, thanks for your tutorial.
    The link for download, its giving me 404 error:
    Where can i download source code ?

  • Thanks for your tutorial brother, solved my problem

  • Thanks you’r tutorial, problem my phone is solved.. very2 thakz :*

  • Wonderful goods from you, man. I’ve understand your stuff previous
    to and you’re just too fantastic.

  • Thks brother, your tutorial solved my problem.. :*

  • Thx..bro :)

  • ali khan

    A new web page has to do their best to get initial hyperlinks from excellent websites or weblogs and get observed. But once you start getting hyperlinks, be it through promotions or without even striving for them, most of other excellent websites will like to cover your items and place your weblink on their websites. more

  • Danielgrant

    Some of these methods include seamless incorporation of search phrases in articles, re-writing of Meta data, and enhancing website material. Discover More

  •,fiyat uygunlugu ve imalattan.profesyonel ekip eşliğinden güvenilir işler yapılmaktadır

  • yuvaraj singh

    Thanks for sharing this informative content ,
    Leanpitch provides online training in Devops during this lockdown period everyone can use it wisely.
    Devops Online Training