backbone.js 学习

资源路径:

backbone入门教程:http://blog.csdn.net/column/details/backbone-js-tutorial.html

backbone中文API:http://www.css88.com/doc/backbone/

underscore.js中文API:http://www.css88.com/doc/underscore/

一、backbone.js的简单认识:

Backbone唯一重度依赖的是Underscore.js 

backbone.js提供了一套web开发的框架,通过Models进行key-value绑定及custom(定制)事件处理,通过Collections提供一套丰富的API用于枚举功能,通过Views来进行事件处理及与现有的Application通过RESTful JSON接口进行交互.它是基于jquery和underscore的一个js框架。

backbone的三个部分:view、model、collection,以后都会提到,这里只要了解,model代表一个数据模型,collection是模型的一个集合,而view是用来处理页面以及简单的页面逻辑的。

二、工作原理:

通过backbone,你可以把你的数据当作Models,通过Models你可以创建数据,进行数据验证,销毁或者保存到服务器上。当界面上的操作引起model中属性的变化时,model会触发change的事件;那些用来显示model状态的views会接受到model触发change的消息,进而发出对应的响应,并且重新渲染新的数据到界面。

三、MVC示例:(http://www.cnblogs.com/hiddenfox/archive/2012/08/19/2646520.html

我的 HTML
















 


backbone.demo


	

我的css

.error {
	color:#E33E06;
}
#main{
	width:800px; 
	margin:0 auto;
	padding:10px;
}
#left{
	float:left;
	width:300px;
	border: 1px solid #000;
	display:inline-block;
	background:#eeeeee;
}
#right{
	float:left;
	margin-left:10px;
	padding:0 20px;
	width:430px;
	display:inline-block;
	border: 1px solid #000;
	background:#eeeeee;
}
h3{
	text-align:center;
}
ul{
	padding:0px;
}
li {
	list-style-type:none;
}
#user-list li{
	height:25px;
}
#user-list li span{
	margin-right:10px;
}
button{
	margin-left:40px;
}
#user-info input, #user-info button{
	display:none;
}
#user-info span{
	display:inline-block;
}
.editing span{
	display:none !important;
}
.editing input, .editing button{
	display:inline-block !important;
}
.editing li:first-child span{
	display:inline-block !important;
}
span.error, span.hint, span.success{
	display:inline-block !important;
}

#uesrInfo{
	margin-left:10px;
	margin-top:20px;
	padding:0 20px;
	width:430px;
	display:inline-block;
	border: 1px solid #000;
	background:#eeeeee;
}
我的js

$(document).ready(function() { 
	
	//定义User
	var User = Backbone.Model.extend({
		validate : function(attrs) { // 验证属性是否合法
			$("#name_error").empty();
			if (attrs.username.length<4 || attrs.username.length>8) {
				$("#name_error").append("名字长度4-8");
				return "Username contains 4-8 characters.";
			}
			/*var obj = $.ajax({
				url : "./rest/user/validate/" + attrs.username, 
				async : false,
			});
			if (obj.responseText == "false") {
				return "Username has been used.";
			}*/
			if (attrs.password.length<5 || attrs.password.length>12) {
				return "Password contains 5-12 characters.";
			}
			if (attrs.email.length == 0) {
				return "Please enter your email.";
			}
			/*if(!attrs.email.match(/^\w{3,}@\w+(\.\w+)+$/)){
				return "Invalid email format.";
			}*/
		},
	});
	
	//定义UserList,是User的集合
	var UserList = Backbone.Collection.extend({
		model : User,
		url : "/", 
		/*****重载fetch****
		fetch : function() {
			var self = this;
			$.ajax({
				url: self.url,
	            cache:false,
				type: 'GET',
				async: true,
				dataType: 'json',
				timeout: 300000,
				success: function( data, textStatus ) {							
					self.reset(data.user);
				},		
			});
		}
		*************/
		fetch : function() {
			var self = this;
			//模拟ajax查询 返回user
			var user  = new User({
				"id":"1",
				"username":"Dason",
				"password":"123456",
				"email":"[email protected]",
				"phone":"456",
			});
			self.reset(user);
		},
	});
	
	//② define UserInfoView, used to display user info
	var UserInfoView = Backbone.View.extend({
         el : $("#uesrInfo"),
         userInfoTemplate : _.template($("#user-info-template").html()),
         
		 render : function(){
             this.$el.html(this.userInfoTemplate(this.model.toJSON()));
             return this;
         },
		 
		//③ Edit
		events : {
			"click #edit" : "displayEdit",
			"click #edit-submit" : "submitEdit",
		},
		//改变 class,显示表单
		displayEdit : function() { 
            this.$("#user-info").addClass("editing");
        },
		
		submitEdit : function(){
			/*this.model.save({ 
                 "username":$("input[name='username']").val(),
                 "password":$("input[name='password']").val(),
                 "email":$("input[name='email']").val(),        
             });*/
			 //模拟save()方法
			 
             this.$("#user-info").removeClass("editing"); //改变 class,隐藏表单
		},
		
		initialize : function() { 
            this.model.bind('change', this.render, this); 
			 this.model.bind('destroy', this.remove, this);
         },
     });
	
	//① define UserItemView,used to display one user item
	var UserItemView = Backbone.View.extend({
		tagName : "li",
		userItemTemplate : _.template($("#user-item-template").html()), 
		
		render : function() {
			this.$el.html(this.userItemTemplate(this.model.toJSON()));
			return this;
		},
		
		events : { 
			//② display user info
            "click a" : "displayInfo", 
			//④ delete user item
			"click #delete-submit" : "clear", 
         },
		 
         initialize : function() { 
            this.userInfoView = new UserInfoView({model : this.model}); //传入当前点击对象
			this.model.bind('destroy', this.remove, this);
			this.model.bind('change', this.render, this);
         },
		 
		 displayInfo : function() { 
            if(_.isEmpty(userInfoView)){
                userInfoView = new UserInfoView({model : this.model});
            }else{
                userInfoView.model = this.model;
                userInfoView.model.unbind('change');
                userInfoView.model.bind('change', this.render, this);
                userInfoView.model.bind('change', userInfoView.render, userInfoView);
            }
            userInfoView.render();
         },
		 
		 clear : function(){
			 this.model.destroy();
		 },
	});
	
	//① define UserListView, used to display users list
	var UserListView = Backbone.View.extend({
		el : $("#main"),
		
		events : {
		     "click #add-submit" : "submitUserForm", //add new user and validate
		},
		
		initialize : function() {
			this.userList = new UserList();
			this.userList.bind('reset', this.addAll, this);
			this.userList.bind('add', this.addOne, this);
			this.userList.bind('all', this.render, this); 
			this.userList.fetch({silent: true, success:function(collection, response){ 
				if(response != null){
					collection.reset(response.user);
				}else{
					userListView.render();
				}
			}});
		},
		
		render : function() {
			this.$("#left h3").html("Total Number:"+this.userList.length);
		},
		
		addOne : function(user) {
			var view = new UserItemView({model : user});
			this.$("#user-list").append(view.render().el);
		},
		
		addAll : function() { 
			this.userList.each(this.addOne);
		},
		
		submitUserForm : function() {
			debugger
			var user  = new User({
				"id":$("input[name='id']").val(),
				"username":$("input[name='username']").val(),
				"password":$("input[name='password']").val(),
				"email":$("input[name='email']").val(),
				"phone":$("input[name='phone']").val(),
			});
			
			var m = this.model; 
			// create model and save on server as well as add the model to Collection
			// and it wiil trigger validate
			this.userList.create(user,{
				wait : true, //wait 为 true 的时候会在回调函数 success 执行的时候才将 model 加到 collection 中
				error : function(m,error) { //显示错误信息
					$(".error").html(error);
				},
				/*success : function() {
					$("input[name='username']").val(""),
					$("input[name='password']").val(""),
					$("input[name='email']").val(""),
				}*/	
			});
			//模拟add new user , in fact,it is implements success(cerate() 'success' callback )  
			if($(".error").text()==""){
				this.userList.add(user);
			};
			
		},
		
	});
	
	var userListView = new UserListView();
	var userInfoView;
});






你可能感兴趣的:(JavaScript)