9951 explained code solutions for 126 technologies

backbone.jsHow do I create a sample application using Backbone.js?

Creating a sample application using Backbone.js involves several steps.

  1. Include the Backbone.js library in the HTML file.
    <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
  2. Create a model to define the data structure for the application.
    var Person = Backbone.Model.extend({
    defaults: {
    name: '',
    age: 0
  3. Create a collection to store the model instances.
    var People = Backbone.Collection.extend({
    model: Person
  4. Create a view to render the model and handle user input.
    var PeopleView = Backbone.View.extend({
    tagName: 'ul',
    render: function(){
      var personView = new PersonView({ model: person });
    }, this);
    return this;
  5. Instantiate the model, collection and view.
    var person = new Person({ name: 'John Doe', age: 30 });
    var people = new People([person]);
    var peopleView = new PeopleView({ collection: people });
  6. Render the view.
  7. Output:
<div id="container">
    <li>John Doe, 30</li>

Helpful links

Edit this code on GitHub