Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / HTML5, CSS3, and JavaScript /

Backbone.js Wine Cellar tutorial – Part 2: CRUD

by Christophe Coenraets

Christophe Coenraets
  • http://coenraets.org/blog/

Content

  • Adding Create, Update, and Delete features
  • Where to go from here

Created

19 March 2012

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
HTML5 JavaScript

Requirements

Prerequisite knowledge

  • Sample files:
  • Download the source code for Part 2 of the Wine Cellar application on GitHub.
  • You will need the RESTful services to run this application. A PHP version (using the Slim framework) is available as part of the download.
  • You can download different versions of the Wine Cellar application:
    • Download a version of this application with a Java back-end (using JAX-RS and Jersey) on GitHub. Read about the Java version of this application in my blog post, Using Backbone.js with a RESTful Java Back-End.
    • Download the non-Backbone Java back-end or the PHP back-end.

User level

All

In Part 1: Getting started of this tutorial, we set up the basic infrastructure for the Wine Cellar application. The application so far is read-only, and thus it only allows you to retrieve a list of wines and display the details of the wine you select.

In this second installment, you will add the ability to create, update, and delete (CRUD) wines.

HTTP Method

URL

Action

GET

/api/wines

Retrieve all wines

GET

/api/wines/10

Retrieve wine with id == 10

POST

/api/wines

Add a new wine

PUT

/api/wines/10

Update wine with id == 10

DELETE

/api/wines/10

Delete wine with id == 10

A PHP version of these services (using the Slim framework) is available as part of the download. A similar Java version of the API (using JAX-RS) is available as part of this post.

Using Backbone.js with non-RESTful Services

If your persistence layer is not available through RESTful services, you can override Backbone.sync. From the 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.”

I do not discuss using non-RESTful services in this tutorial. See the documentation for more information.

Adding Create, Update, and Delete features

You can run the application that you will code in this tutorial.  The create, update, delete features are disabled in this online version.

Here is the code for Part 2. I discuss key changes below.

Figure 2. The backbone.js code
Figure 2. The backbone.js code

Code highlights

Wine (lines 2-14)

Part 2 adds two attributes to the Wine Model, as follows:

  • urlRoot (line 3): The RESTful service endpoint to retrieve or persist Model data. Note that this attribute is only needed when retrieving/persisting Models that are not part of a Collection. If the Model is part of a Collection, the url attribute defined in the Collection is enough for Backbone.js to know how to retrieve, update, or delete data using your RESTful API.
  • Defaults (line 4): Default values used when a new instance of the model is created. This attribute is optional. However, it was required in this application for the wine-details template to render an “empty” wine model object (which happens when adding a new wine).

WineListView (lines 22-40)

When user adds a new wine, you want it to automatically appear in the list. To make that happen, bind the View to the add event of the WineListView model (which is the collection of wines). When that event is fired, the application creates and adds a new instance of WineListItemView to the list.

WineListItemView (lines 42-62)

  • When a user changes a wine, you want the corresponding WineListItemView to re-render automatically to reflect the change. To make that happen, bind the View to the change event of its model, and execute the render function when the event is fired. Similarly, when a user deletes a wine, you want the list item to be removed automatically.
  • To make that happen, bind the view to the destroy event of its model and execute our custom close function when the event is fired.
    Important: To avoid memory leaks and events firing multiple times, it is important to unbind the event listeners before removing the list item from the DOM.
  • Note that in either case you don’t have the overhead of re-rendering the entire list. You only re-render or remove the list item affected by the change.

WineView (lines 64-123)

In the spirit of encapsulation, the event handlers for the Save and Delete buttons are defined inside WineView, as opposed to defining them as free-hanging code blocks outside the “class” definitions. Use the Backbone.js Events syntax, which uses the jQuery delegate mechanism behind the scenes.

There are always different approaches to update the model based on user input in a form:

  • “Real time” approach: You use the change handler to update the model as changes are made in the form. This is in essence bi-directional data binding. The model and the UI controls are always in sync. Using this approach, you can then choose between sending changes to the server in real time (implicit save), or wait until the user clicks a Save button (explicit save). The first option can be chatty and unpractical when there are cross-field validation rules. The second option may require you to undo model changes if the user navigates to another item without clicking Save.
  • “Delayed” approach: You wait until the user clicks Save to update the model based on the new values in UI controls and then send the changes to the server.

This discussion is not specific to Backbone.js and is therefore beyond the scope of this post. For simplicity, I used the delayed approach here. However I still wired the change event, and use it to log changes to the console. I found this very useful when debugging the application, and particularly to make sure I had cleaned up my bindings (see the close function).  If you see the change event firing multiple times, you probably didn’t clean up your bindings appropriately.

HeaderView (lines 125-148)

Backbone.js Views are typically used to render domain models (as done in WineListView, WineListItemView, and Wine View). But they can also be used to create composite UI components. For example, in this application, we define a Header View (a toolbar) that could be made of different components and which encapsulates its own logic.

Where to go from here

The application so far doesn’t support deep-linking. For example, it doesn’t include the functionality to select a wine in the list, grab the URL in the address bar and paste it in another browser window: these features don’t yet work. In Part 3: Deep linking and application states, you will add complete support for deep linking.

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This

  • Introducing the HTML5 storage APIs
  • Introducing theexpressiveweb.com beta
  • Adobe, standards, and HTML5
  • Developing HTML5 games with Impact JavaScript game engine and Dreamweaver CS5.5
  • Using the Geolocation API
  • CSS3 basics
  • Real-time data exchange in HTML5 with WebSockets
  • JavaScript object creation: Learning to live without "new"
  • Object types in JavaScript
  • Pseudo-classical object-oriented programming in JavaScript with Minion

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement