backbone.js 学习

来源:互联网 发布:ie8登录不了淘宝 编辑:程序博客网 时间:2024/05/19 03:30

资源路径:

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

<html><head><!-- remote origin/master from github --><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><script src="./js/jquery.js"></script><script src="./js/underscore.js"></script><script src="./js/backbone.js"></script><!--<script src="./js/addUserAndValidate.js.js"></script>--><!--<script src="./js/addUserAndDisplay.js"></script>--><script src="./js/addEditAndDelete.js"></script><!-- userList html模板 --><script type="text/template" id="user-item-template"> <button id="delete-submit">del</button><span>(<%= id %>)</span> <a href="#"><%= username %></a></script><!-- 展示User详细信 HTML模板 --> <script type="text/template" id="user-info-template">     <h3>User Information</h3> <button id="edit">Edit</button>     <ul id="user-info">         <li>ID:<span><%= id %></span></li>         <li>Username:<span><%= username %></span><input type="text" name="username" value="<%= username %>" /></li>         <li>Password:<span><%= password %></span><input type="password" name="password" value="<%= password %>" /></li>         <li>Email:<span><%= email %></span><input type="text" name="email" value="<%= email %>" /></li>         <button id="edit-submit">Submit</button>     </ul> </script><link rel="stylesheet" type="text/css" href="./css/default.css" /><title>backbone.demo</title></head><body><div id="main"><div id="left"><h3></h3><ul id="user-list"></ul></div><div id="right"><h3>add user</h3><p class="error"></p><ul id="user-form" class="editing"><li>ID:<input type="text" name="id" /></li><li>Username:<input type="text" name="username" /><span id="name_error"></span></li><li>Password:<input type="password" name="password" /></li><li>Email:<input type="text" name="email" /></li><button id="add-submit">Submit</button></ul></div><div id ="uesrInfo"><div></div></body></html>
我的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() { //定义Uservar 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查询 返回uservar user  = new User({"id":"1","username":"Dason","password":"123456","email":"122@qq.com","phone":"456",});self.reset(user);},});//② define UserInfoView, used to display user infovar UserInfoView = Backbone.View.extend({         el : $("#uesrInfo"),         userInfoTemplate : _.template($("#user-info-template").html()),          render : function(){             this.$el.html(this.userInfoTemplate(this.model.toJSON()));             return this;         }, //③ Editevents : {"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 itemvar 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 listvar 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() {debuggervar 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 validatethis.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;});






0 0
原创粉丝点击