Here is a short practice on Backbone.js:
- Create an HTML file with a script tag that includes the Backbone.js library.
phpCopy code<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.4.0/backbone-min.js"></script>
</head>
<body>
</body>
</html>
- Create a Backbone Model for a Book, with a title and author attribute.
phpCopy codevar Book = Backbone.Model.extend({
defaults: {
title: "Unknown",
author: "Unknown"
}
});
- Create a Backbone Collection of Books.
cssCopy codevar Books = Backbone.Collection.extend({
model: Book
});
- Create a View for a single Book. The view should display the title and author of the book.
kotlinCopy codevar BookView = Backbone.View.extend({
tagName: "li",
template: _.template("<strong><%= title %></strong> by <%= author %>"),
render: function() {
this.$el.html(this.template(this.model.attributes));
return this;
}
});
- Create a View for the list of Books. The view should display a list of books using the BookView for each book.
javascriptCopy codevar BooksView = Backbone.View.extend({
tagName: "ul",
render: function() {
this.collection.each(function(book) {
var bookView = new BookView({ model: book });
this.$el.append(bookView.render().el);
}, this);
return this;
}
});
- Instantiate a Books collection and a BooksView, and render the view to the page.
javascriptCopy codevar books = new Books([
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald" },
{ title: "To Kill a Mockingbird", author: "Harper Lee" },
{ title: "Pride and Prejudice", author: "Jane Austen" }
]);
var booksView = new BooksView({ collection: books });
$("body").append(booksView.render().el);
This is a simple example of how to use Backbone.js to create a model, collection, and views for a list of books. You can find more information about Backbone.js in the documentation.