Home Web Front-end JS Tutorial Use Backbone.js to create an example code for adding, deleting, modifying and looking up tables

Use Backbone.js to create an example code for adding, deleting, modifying and looking up tables

Apr 27, 2017 pm 03:00 PM

Backbone.js is a heavyweight web development framework. It is a js framework based on jquery and underscore. It mainly consists of three parts: Model, Collection, and View.
1.Model: Create a model to represent the data object, perform data verification, destroy the object or save it to the server.
2.Collection: It is a collection of Models that can add or delete elements, as well as some convenient operations.
3.View: You can bind html templates and events, you can render models or collections onto the page, and you can re-render the page by listening to events such as model changes or destruction.
The advantage of Backbone is that it separates data and interface well, and strips out event bindings, which facilitates management and iteration, making the modularization of Javascript clearer. Backbone is more suitable for situations where there is a large amount of data on the page, making it easier to communicate complex information within the page.

Below I used Backbone to write a table for adding, deleting, modifying, and checking, referring to the Todos example on Backbone's official website. Backbone.js itself relies on jquery and underscore. For data storage, I used backbone-localstorage.js to store data in a local database. I posted the main js code. A lot of jquery, underscore and backbone methods and events are used, please refer to the relevant documents.

$(function(){

	//Model:表示一个学生
	var Student=Backbone.Model.extend({
		//默认值
		defaults:function(){
			return{
				name:"XXX",
				age:"0",
				selected:false,
				id:Students.nextId(),
			};
		},
		
		//初始化的时候判断,如果设置的属性值非法就设为默认值
		initialize:function(){
			if(!this.get("name")){
				this.set({"name":this.defaults().name});
			}
			if(!this.get("age")||!(/(^[1-9]\d*$)/.test(this.get("age")))){
				this.set({"age":this.defaults().age});
			}
		},

		//标记该学生是否被选中
		toggle:function(){
			this.save({selected:!this.get("selected")});
		}
	});

	//Collection:Model的集合,即所有学生的集合
	var Students=Backbone.Collection.extend({
		
		model:Student,
		
		//本地数据库,用到backbone-localstorage.js
		localStorage:new Backbone.LocalStorage("Students-Table"),

		//返回被选中的学生的集合
		selected:function(){
			return this.filter(function(student){return student.get('selected');});
		},

		//给每个学生一个编号
		nextId:function(){
			if(!this.length)
				return 1;
			return this.last().get('id')+1;
		}
	});

	//定义一个学生集合对象
	var Students=new Students;


	//View:这个视图表示table中的一列,即一个学生,对应一个Model
	var StudentView=Backbone.View.extend({
		//表示<tr></tr>元素
		tagName:"tr",
		
		//将相应模板写入template属性中,_.template()为underscore.js中的方法
		template:_.template($(&#39;#item-template&#39;).html()),

		//绑定该tr下的事件
		events:{
			"click .toggle":"toggleSelect",
			"dblclick td":"edit",
			"click a.destroy":"clear",
			"blur .edit":"close"
		},

		//初始化该View,listenTo监听model的事件
		initialize:function(){
			//model发生变化就重新渲染视图
			this.listenTo(this.model,&#39;change&#39;,this.render);
			//销毁model
			this.listenTo(this.model,&#39;destroy&#39;,this.remove);
		},

		//this.$el为该tr节点元素,将template渲染进该节点,并把model的值写入
		render:function(){
			this.$el.html(this.template(this.model.toJSON()));
			//如果该行被选中,则切换样式
			this.$el.toggleClass(&#39;selected&#39;,this.model.get(&#39;selected&#39;));
			return this;
		},

		//判断该行是否被选中,对应model中的selected属性
		toggleSelect:function(){
			this.model.toggle();
		},

		//双击td将样式变为可编辑
		edit:function(e){
			$(e.currentTarget).addClass("editing").find("input,select").focus();
		},

		//编辑状态下失去焦点,则修改完成
		close:function(e){
			var input=$(e.currentTarget);

			if(input.attr(&#39;name&#39;)=="name"){
				if(!input.val()){
					input.val(this.model.defaults().name);
				}
				this.model.save({"name":input.val()});
			}else if(input.attr(&#39;name&#39;)=="gender"){
				this.model.save({"gender":input.val()});
			}else{
				if(!input.val()||!(/(^[1-9]\d*$)/.test(input.val()))){
					input.val(this.model.defaults().age);
				}
				this.model.save({"age":input.val()});
			}
			input.parent().removeClass("editing");
		},

		//删除该行的时候删除相应model
		clear:function(){
			this.model.destroy();
		}
	});


	//View:这个视图表示$("#content"),用来表现整个学生表格
	var AppView=Backbone.View.extend({
		el:$("#content"),

		//右下角删除学生数目的模板
		statsTemplate:_.template($(&#39;#stats-template&#39;).html()),

		events:{
			"click #add-student":"addNewStudent",
			"click #clear-selected":"clearSelected",
			"click #select-all":"selectAll"
		},

		initialize:function(){
			this.allCheckbox=$("#select-all");
			this.main=$("#main");
			this.footer=$(&#39;footer&#39;);
			this.name=$("#new-name");
			this.age=$("#new-age");
			this.gender=$("#new-gender");

			//Collection中增加一个Model就触发add事件
			this.listenTo(Students,&#39;add&#39;,this.addOne);
			//一旦调用fetch方法就触法reset事件
			this.listenTo(Students,&#39;reset&#39;,this.addAll);
			//all事件表示该View下的所有事件,即触法任意事件就触法all事件
			this.listenTo(Students,&#39;all&#39;,this.render);

			//从本地数据库中获取所有学生
			Students.fetch();
		},

		//渲染视图
		render:function(){
			var selected=Students.selected().length;
			
			if(Students.length){
				this.main.show();
				this.footer.show();
				this.footer.html(this.statsTemplate({selected:selected}));
			}else{
				this.main.hide();
				this.footer.hide();
			}
			//判断所有学生是否被选中
			this.allCheckbox.attr("checked",selected==Students.length?true:false);
		},

		//增加一个学生,同时将model传入StudentView中
		addOne:function(student){
			var view=new StudentView({model:student});
			//将渲染后的每一列添加到表格中
			this.$("#student-list").append(view.render().el);
		},

		//增加所有学生,通过Collection.each依次调用addOne方法
		addAll:function(){
			Students.each(this.addOne,this);
		},

		//增加一个新学生
		addNewStudent:function(){
			Students.create({name:this.name.val(),gender:this.gender.val(),age:this.age.val()});
			this.name.val(&#39;&#39;);
			this.age.val(&#39;&#39;);
			this.gender.val(1);
		},

		//删除选中列,_.invoke(集合,方法)
		clearSelected:function(){
			_.invoke(Students.selected(),&#39;destroy&#39;);
		},

		//选中所有
		selectAll:function(){
			var selected=this.allCheckbox.attr(&#39;checked&#39;)=="checked";
			Students.each(function(student){
				student.save({&#39;selected&#39;:selected});
			});
		}
	});

	//创建View
	var App=new AppView;
});
Copy after login

The above is the detailed content of Use Backbone.js to create an example code for adding, deleting, modifying and looking up tables. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles