Mode:
Duration:
1
Coding works best on desktop or with an external keyboard.
Coding works best on desktop or with an external keyboard.
A simple counter using Backbone.js models and views with theme toggle.
var CounterModel = Backbone.Model.extend({
defaults: { count: 0, isDark: false },
increment: function() { this.set('count', this.get('count') + 1); },
decrement: function() { this.set('count', this.get('count') - 1); },
reset: function() { this.set('count', 0); },
toggleTheme: function() { this.set('isDark', !this.get('isDark')); }
});
var CounterView = Backbone.View.extend({
tagName: 'div',
initialize: function() { this.listenTo(this.model, 'change', this.render); },
render: function() {
this.el.className = this.model.get('isDark') ? 'dark-theme' : 'light-theme';
this.el.innerHTML = '<h2>Counter: ' + this.model.get('count') + '</h2>' +
'<div>' +
'<button id="inc">+</button>' +
'<button id="dec">-</button>' +
'<button id="reset">Reset</button>' +
'</div>' +
'<button id="toggle">Switch to ' + (this.model.get('isDark') ? 'Light' : 'Dark') + ' Theme</button>';
this.delegateEvents({ 'click #inc': 'increment', 'click #dec': 'decrement', 'click #reset': 'reset', 'click #toggle': 'toggleTheme' });
return this;
},
increment: function() { this.model.increment(); },
decrement: function() { this.model.decrement(); },
reset: function() { this.model.reset(); },
toggleTheme: function() { this.model.toggleTheme(); }
});
var counter = new CounterModel();
var view = new CounterView({ model: counter });
document.body.appendChild(view.render().el);Backbone.js is a lightweight JavaScript MVC framework that provides structure to web applications using Models, Collections, Views, and Events. It helps developers build organized, maintainable SPAs with minimal boilerplate and strong conventions.
Origin & Creator
Created by Jeremy Ashkenas (also creator of Underscore.js and CoffeeScript) and released by DocumentCloud in 2010.
Industrial Note
Backbone is great for small-to-medium-scale web apps, legacy systems, low-dependency environments, and scenarios requiring simple MVC architecture with minimal overhead.