ArticleZip > Simplest Of Backbone Js Examples

Simplest Of Backbone Js Examples

Backbone.js is a popular JavaScript library that helps you organize your code and create structured web applications with ease. In this guide, we'll walk you through some simple examples to help you get started with Backbone.js.

Let's dive right in with a basic example. Imagine we have a simple task list application where users can add tasks to a list. To begin, we define a model for our task like so:

Javascript

var Task = Backbone.Model.extend({
  defaults: {
    title: '',
    completed: false
  }
});

In this code snippet, we are creating a `Task` model with two default properties: `title` and `completed`. The `defaults` object allows us to define initial values for our model attributes.

Next, we move on to creating a collection of tasks:

Javascript

var TaskList = Backbone.Collection.extend({
  model: Task
});

Here, we're defining a `TaskList` collection that will hold instances of our `Task` model. Collections in Backbone are used to manage sets of models.

Now, let's create a simple view to display our tasks:

Javascript

var TaskView = Backbone.View.extend({
  tagName: 'li',
  template: _.template($('#task-template').html()),
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

In this code snippet, we define a `TaskView` view that represents a single task in our application. We specify that each task will be displayed as a list item (`li`) and use an HTML template to render the task's title.

To display our collection of tasks, we need to create a view for the entire task list:

Javascript

var TaskListView = Backbone.View.extend({
  el: '#task-list',
  initialize: function() {
    this.listenTo(this.collection, 'add', this.renderTask);
  },
  render: function() {
    this.collection.each(this.renderTask, this);
    return this;
  },
  renderTask: function(task) {
    var taskView = new TaskView({ model: task });
    this.$el.append(taskView.render().el);
  }
});

In the code above, we define a `TaskListView` view to render the entire list of tasks. We specify where the view will be appended in the DOM (in this case, an element with the ID `task-list`) and define methods for rendering individual tasks as well as the entire task list.

Finally, we create instances of our models, collections, and views to bring it all together:

Javascript

var task1 = new Task({ title: 'Complete tutorial' });
var task2 = new Task({ title: 'Practice Backbone.js' });

var taskList = new TaskList([task1, task2]);

var appView = new TaskListView({ collection: taskList });
appView.render();

Congratulations! You have successfully created a simple task list application using Backbone.js. Feel free to explore more features of Backbone.js and enhance your applications further. Happy coding!