1. Home
  2. /
  3. Backbone-js
  4. /
  5. Backbone.js Counter with Max Limit

Backbone.js Counter with Max Limit - Backbone-js Typing CST Test

Loading…

Backbone.js Counter with Max Limit — Backbone-js Code

Stops incrementing after a maximum count is reached.

var CounterModel = Backbone.Model.extend({
	defaults: { count: 0 },
	max: 5,
	increment: function() { if(this.get('count') < this.max) this.set('count', this.get('count') + 1); },
	decrement: function() { this.set('count', this.get('count') - 1); },
	reset: function() { this.set('count', 0); }
});

var CounterView = Backbone.View.extend({
	tagName: 'div',
	initialize: function() { this.listenTo(this.model, 'change', this.render); },
	render: function() {
		this.el.innerHTML = '<h2>Counter: ' + this.model.get('count') + '</h2>' +
		'<button id="inc">+</button>' +
		'<button id="dec">-</button>' +
		'<button id="reset">Reset</button>';
		this.delegateEvents({ 'click #inc': 'increment', 'click #dec': 'decrement', 'click #reset': 'reset' });
		return this;
	},
	increment: function() { this.model.increment(); },
	decrement: function() { this.model.decrement(); },
	reset: function() { this.model.reset(); }
});

var counter = new CounterModel();
var view = new CounterView({ model: counter });
document.body.appendChild(view.render().el);

Backbone-js Language Guide

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.

Primary Use Cases

  • ▸Single-page applications with light structure
  • ▸Legacy jQuery-based frontends
  • ▸Apps requiring minimal dependencies
  • ▸Projects needing manual control over architecture
  • ▸Incrementally structuring existing codebases

Notable Features

  • ▸Lightweight MVC architecture
  • ▸Models with custom events
  • ▸Collections for list handling
  • ▸Views for UI rendering and events
  • ▸RESTful JSON syncing with servers

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.

More Backbone-js Typing Exercises

Backbone.js Counter ComponentBackbone.js Counter with Step IncrementBackbone.js Counter with Theme Toggle OnlyBackbone.js Counter with HistoryBackbone.js Counter with Auto-ResetBackbone.js Counter with Auto-IncrementBackbone.js Counter with Conditional ThemeBackbone.js Full Featured Counter

Practice Other Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypher