backbone js

hljs.initHighlightingOnLoad();

Backbone.js

Backbone.js is a lightweight JavaScript library that allows you to structure your code in a clean and organized way. It provides models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Models

Models in Backbone.js represent a single data record. They provide key-value binding, validation, and custom events. Models can be synced with the server over a RESTful JSON interface.


			var Todo = Backbone.Model.extend({
				defaults: {
					title: '',
					completed: false
				},
				initialize: function() {
					console.log('New todo created.');
				}
			});
		

Collections

Collections in Backbone.js are ordered sets of models. They provide a rich API of enumerable functions and can be synced with the server over a RESTful JSON interface.


			var TodosCollection = Backbone.Collection.extend({
				model: Todo,
				url: '/todos'
			});
		

Views

Views in Backbone.js are responsible for rendering your data to the DOM. They provide declarative event handling and can be bound to model and collection events.


			var TodoView = Backbone.View.extend({
				tagName: 'li',
				events: {
					'click .toggle': 'toggleCompleted'
				},
				initialize: function() {
					this.listenTo(this.model, 'change', this.render);
				},
				render: function() {
					this.$el.html(this.model.get('title'));
					this.$('.toggle').prop('checked', this.model.get('completed'));
					return this;
				},
				toggleCompleted: function() {
					this.model.set('completed', !this.model.get('completed'));
				}
			});
		

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe