Tuesday, November 22, 2011

iOS App Development with PhoneGap and Spine Mobile: Example App



Alex MacCaw, the creator of Spine and author of O'Reilly's JavaScript Web Applications, has a simple example of a mobile contact application. We'll set this application up, add a little functionality, and eventually wrap it in PhoneGap as a iOS app for the iPhone.

There's an explanation on spinejs.com you can follow for a thorough explanation of the application. 


Let's get it setup and running locally.
  1. Download the app from github.com. My copy is under ~/Documents/spine.mobile.contacts/.
  2. Open a terminal and change to the spine.mobile.contacts directory.
    $ cd ~/Documents/spine.mobile.contacts
  3. Install the local npm modules
    $ npm install .
  4. Start the hem server
    $ hem server
  5. Browse to the application at http://localhost:9294/
You should now see this...


Go ahead and add a few contacts. HTML5 local storage is used to persist the data.

Now, let's add a way to delete contacts. Open contacts.coffee located in the ~/Documents/spine.mobile.contacts/app/controllers/ directory with a text editor. We want to add a delete button to the ContactsShow class. ContactsShow is the controller for the panel that displays an individual contact when you click on a contact in the list view.

The changes are pretty simple.

class ContactsShow extends Panel
  className: 'contacts showView'

  constructor: ->
    super

    Contact.bind 'change', @render

    @active @change

    @addButton('Back', @back)
  
    # Delete button placed to the right with a callback 
    # to a delete function
    @addButton('Delete', @delete).addClass('right')

  render: =>
    return unless @item
    @html require('views/contacts/show')(@item)

  change: (params) ->
    @item = Contact.find(params.id)
    @render()

  # Delete callback function
  # Confirm the delete, then navigate back to the list view
  # If they change their mind, stay here
  delete: (params) ->
    if confirm('Are you sure?')
      @item.destroy() 
      @navigate('/contacts', trans: 'left')

  back: ->
    @navigate('/contacts', trans: 'left')

Save your changes. There's no need to restart the hem server. Just reload the site in the browser, hem dynamically picks up the changes with each request.

Click on a contact, the item view displays with the delete button on the top right.

Click the delete button. You should see a confirmation dialog...
Click cancel and you'll see the item view. Click ok, the contact is deleted and the list view is redisplayed.

In my next blog post I'll finish wrapping the app in PhoneGap.


No comments:

Post a Comment