VersionOne API 101: Fetch a Story by ID with Backbone.js

The simplest thing that could possibly work! 25 lines of CoffeeScript to use the VersionOne REST API with Backbone.js and its Model class and Backbone.sync API.

by JoshGough

HTML

<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone-min.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="https://raw.github.com/powmedia/backbone-forms/master/distribution/backbone-forms.js"></script>
<script src="https://raw.github.com/powmedia/backbone-forms/master/distribution/editors/list.js"></script>
<script src="https://raw.github.com/powmedia/backbone-forms/master/distribution/adapters/backbone.bootstrap-modal.js"></script>
<script src="https://raw.github.com/powmedia/backbone-forms/master/distribution/templates/bootstrap.js"></script>
<h3>"Simplicity--the art of maximizing the amount of work not done--is essential."</h3> 
<blockquote>-- <a href="http://agilemanifesto.org" target="_blank">The Agile Manifesto</a></blockquote>

<div id="output"></div>

CoffeeScript

urlRoot = "http://eval.versionone.net/platformtest/rest-1.v1/Data/Story/"
headers = { Authorization: "Basic " + btoa("admin:admin"), Accept: "haljson" }
attributes = ['Name', 'Description', 'Estimate', 'RequestedBy']
storyId = 1154

StoryModel = Backbone.Model.extend(
    urlRoot: urlRoot
    url: ->
        return @urlRoot + @id if @hasChanged() and not @isNew()
        args = {}
		# NOTE: Just for demo (would not likely have the select, where stuff on a single model, but on a collection)
        if @select?
            args.sel = @select if _.isString(@select)
            args.sel = @select.join ',' if _.isArray(@select)
        if @where?
            args.where = @where if _.isString(@where)
            args.where = ($.param(@where).replace(',', ';')) if _.isObject(@where)
        return @urlRoot + @id if _.isEmpty args
        return @urlRoot + @id + '?' + $.param args
    save: (attributes, options) ->
        options or options = {}
        _.defaults options, { contentType: 'haljson', patch: true, headers: headers }
        Backbone.Model::save.call this, attributes, options
    fetch: (options) ->
        options or options = {}
        _.defaults options, { dataType: 'json', headers: headers }
        console.log options
        if options.select?
            @select = options.select
            delete options.select
        if options.where?
            @where = options.where
            delete options.where        
        Backbone.Model::fetch.call this, options
)

storyModel = new StoryModel
storyModel.id = storyId
options =
    select: attributes

storyModel.fetch(options).done (data) ->
    $('#output').html('<pre>' + JSON.stringify(data, null, 4) + '</pre>')