Saturday, August 4, 2012

backbone.js & couchdb

This blog post is about some code I wrote to solve a problem.  I didn't care for the existing solutions, but I now think that I don't care for the problem.

My initial interest in backbone was as a tool to quickly prototype UI couchapps.  Specifically I wanted an easy way to modify collections of documents in CouchDB on a web page.  Unfortunately, that wasn't as easy as I expected.  So here's some of what I learned thus far.

Using jshint or jslint will save time.  I've spent hours debugging JavaScript in the browser (which is less painful thanks to Firebug and Chrome) and hours debugging JavaScript in PhoneGap projects.  Debugging syntax mistakes in a chromeless browser over ADB is a nightmare.

Writing test cases for async code is a nightmare.  Qunit sucks for async testing, but is a great tool otherwise (haven't tried jasmine yet).  The right solution is to test with node (specifically using mocha).  So, I had to learn a little about node and here's the magic.

setup(function(done) {

The setup function takes a parameter called done, which indicates setup contains async code and is also a callback to indicate the async code is complete.

Separate a ReSTful interface into components.  Don't make one giant method for everything, separate create/read/update/delete into methods invoked from sync: 

    Couch.Model.prototype.sync = function(method, model, opts) { 
        if (debug); 
        switch (method) { 
        case "read": 
            return, model, opts); 
        case "create": 
            return, model, opts); 
        case "update": 
            return, model, opts); 
        case "delete": 
            return, model, opts); 
This is good practice for server side code too.  Separate the storage layer from API so that the storage layer can be used outside the API.  The reason I mention this is that most Backbone users will probably implement server side ReST views rather than Backbone.sync.

Why are id and rev sometime prefaced with an _?  Seriously, why is there an _ sometimes?

99% of all applications require a server-side controller with record read access.

No comments:

Post a Comment