Here is a short tutorial on how to get started with Backbone.js:
- Set up the project:
Create a new directory for your project and initialize it with npm:
csharpCopy codenpm init
- Install Backbone.js:
Install Backbone.js and its dependencies using npm:
Copy codenpm install backbone jquery underscore
- Create a Backbone Model:
Create a file named model.js
and define a Backbone Model:
javascriptCopy codevar Backbone = require("backbone");
var Model = Backbone.Model.extend({
defaults: {
title: "",
completed: false
}
});
module.exports = Model;
This model represents a simple to-do item, with a title and a completion status.
- Create a Backbone Collection:
Create a file named collection.js
and define a Backbone Collection:
javascriptCopy codevar Backbone = require("backbone");
var Model = require("./model");
var Collection = Backbone.Collection.extend({
model: Model
});
module.exports = Collection;
This collection will store a list of to-do items.
- Create a Backbone View:
Create a file named view.js
and define a Backbone View:
javascriptCopy codevar Backbone = require("backbone");
var Collection = require("./collection");
var View = Backbone.View.extend({
el: "#todo-list",
initialize: function() {
this.collection = new Collection();
this.render();
},
render: function() {
this.collection.each(function(model) {
this.$el.append("<li>" + model.get("title") + "</li>");
}, this);
}
});
module.exports = View;
This view will display a list of to-do items in the element with the ID todo-list
.
- Create the HTML page:
Create an HTML page named index.html
with the following content:
htmlCopy code<!DOCTYPE html>
<html>
<head>
<script src="node_modules/jquery/dist/jquery.js"></script>
<script src="node_modules/underscore/underscore.js"></script>
<script src="node_modules/backbone/backbone.js"></script>
<script src="./model.js"></script>
<script src="./collection.js"></script>
<script src="./view.js"></script>
</head>
<body>
<ul id="todo-list"></ul>
<script>
var view = new View();
</script>
</body>
</html>
- Start a local web server:
Use a local web server to serve the HTML page. One option is to use the http-server
npm package:
Copy codenpm install http-server -g
http-server
Open your browser and navigate to `http://localhost:8080