// Here is our Backbone model!
Book = Backbone.Model.extend({
urlRoot: '/book'
});
$(function() {
do_create();
});
function do_create() {
echo("
Creating a book:
");
var book = new Book;
book.set({ title: "Darkly Dreaming Dexter", author: "Jeff Lindsay" });
book.save({}, {
error: onerror,
success: function() {
print_book(book);
echo("Retrieving the same book:
");
do_retrieve(book);
}
});
}
function do_retrieve(_book) {
var book = new Book({ id: _book.id });
book.fetch({
error: onerror,
success: function() {
print_book(book);
do_edit_error(book);
}
});
}
function do_edit_error(book) {
echo("Editing book with an error:
");
console.log("(You should see an HTTP error right about here:)");
book.set({ author: '' });
book.save({}, {
success: onerror,
error: function() {
console.log("(...yep.)");
echo("...yes, it occured.");
do_edit(book);
}
});
}
function do_edit(book) {
echo("Editing book:
");
book.set({ author: 'Anne Rice', title: 'The Claiming of Sleeping Beauty' });
book.save({}, {
error: onerror,
success: function() {
print_book(book);
do_delete(book);
}
});
}
function do_delete(book) {
echo("Deleting book:
");
book.destroy({
error: onerror,
success: function() {
echo("Success.");
do_verify_delete(book.id);
}
});
}
function do_verify_delete(id) {
echo("Checking if book "+id+" still exists:
");
console.log("(You should see an HTTP error right about here:)");
var book = new Book({ id: id });
book.fetch({
success: onerror,
error: function() {
console.log("(...yep.)");
echo("No, it doesn't.");
do_success();
}
});
}
function do_success() {
echo("Success!
");
}
function print_book(book) {
echo("- Title:
- "+book.get('title')+"
");
echo("- Author:
- "+book.get('author')+"
");
echo("- ID:
- "+book.get('id')+"
");
}
// Helper functions
function echo(html) {
$("#messages").append(html);
};
function onerror() {
echo("Oops... an error occured.
");
};