Demo介绍

学习了如何基本的使用Backbone,展示用户信息

使用JQuery操作DOM,backbone.localStorage.js操作localstorage

大体实现

•创建user Model

 var User = Backbone.Model.extend({
defaults: {
username: '小强'
},
initialize: function() {
if (!this.get("username")) {
this.set({"username": this.defaults.username});
}
if (!this.get("userid")) {
this.set({"userid": ++userid});
}
}
});

•创建user Collection管理users

 var UserCollection = Backbone.Collection.extend({
model: User,
// 持久化到本地数据库
localStorage: new Store("users")
});

•创建View

按功能页划分:

- 列表页

- 添加(修改)页

- 详情页

创建基础View

 var View = Backbone.View.extend({
register:function (state) {
this.state = state;
return this;
}
});

创建User Item 视图

 var UserItemView = View.extend({
tagName: 'li', // 放view展示内容的外层容器,默认div
template: _.template($('#user-item-template').html()),
render: function () { // 渲染
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events:{ // 事件列表
'click .removeUser': 'deleteUser',
'click .viewUser': 'viewUser'
},
viewUser: function() {
this.state.trigger('viewUser', this.model);
},
deleteUser: function() {
this.state.trigger('removeUser', this.model);
this.remove();
}
});

创建User list 视图,该视图可创建user item view

 var userListView = View.extend({
template: _.template($('#list-template').html()),
initialize: function() {
var view = this;
this.state = new Backbone.Model(); // 实例化一个model
this.router = this.options.router;
// 调用fetch触发reset
this.collection.unbind('reset');
this.collection.bind('reset', this.addAll, this);
setTimeout(function(){
view.collection.fetch();
},0);
},
render: function() {
var view = this;
this.$el.html(this.template(this.state.toJSON()));
// 服务器同步
this.state.on('removeUser', function(user) {
user.destory();
view.collection.remove(user);
});
this.state.on('viewUser', function(user) {
view.router.navigate('user/' + user.cid, {trigger:true});
}); return this;
},
createUserItemView: function(user) {
var userItemView = new UserItemView({
model: user
});
userid = Math.max.call(null, user.get('userid'),userid);
userItemView.register(this.state).render().$el.appendTo($('#list'));
},
addAll: function() {
this.collection.each(this.createUserItemView.bind(this));
}
});

User Modify 视图

 var UserModifyView = View.extend({
template: _.template($('#modify-template').html()),
initialize: function() {
this.router = this.options.router;
},
render: function() {
var view = this;
if(this.model) {
this.$el.html(this.template(this.model.toJSON()));
}
else {
this.$el.html(this.template({username: ''}));
}
setTimeout(function() {
view.$el.find('input').focus().select(); //设置焦点并选中
}, 0);
return this;
},
events: {
'click a.add': 'modify'
},
modify: function(){
var view = this;
if(this.model){
this.model.save({'username': this.$el.find('input').val()});
}
else {
this.router.userCollection.create(new User({
username:view.$el.find('input').val(),
userid: ++userid
}));
}
this.router.navigate('list', {trigger:true}); // 跳转至list
}
});

User Detail 视图

 var UserView = View.extend({
template: _.template($('#user-template').html()),
initialize: function(){
this.router = this.options.router;
},
render: function(){
var view = this;
this.$el.html(this.template(this.model.toJSON()));
return this;
},
events: {
'click .editUser': 'editUser'
},
editUser: function() {
this.router.navigate('edit/' + this.model.cid, {trigger:true});
this.remove();
}
});

注:以上使用的backbone版本是0.9.2,该版本Backbone.View中可导出options属性,但1.1.2 版本已不再提供该属性

因此,View的定义、实例化可改为:

 var UserListView = View.extend({
...
initialize: function() {
var view = this;
this.state = new Backbone.Model();
this.router = this.attributes.router; // 使用attributes属性获取
...
}
...
}) this.currentView = new UserListView({
collection: router.userCollection,
attributes:{router:router} // 使用attributes属性传递
}).render().$el.appendTo($(this.el));

•Router 控制器

使用控制器将定义的类进行组合

 var App = Backbone.Router.extend({
initialize: function(el) {
this.el = el;
this.userCollection = new UserCollection();
},
routes: {
'': 'list',
'list': 'list',
'add': 'edit',
'edit/:cid': 'edit',
'user': 'user',
'user:/:cid': 'user'
},
list: function() {
var router = this;
this.clean();
this.currentView = new UserListView({
collection: router.userCollection,
router:router
}).render().$el.appendTo($(this.el));
},
edit: function(cid) {
var router = this,
user = null;
this.clean();
if(cid){
user = router.userCollection.getByCid(cid);
}
this.currentView = new UserModifyView({
model:user,
router:router
}).render().$el.appendTo($(this.el));
},
user: function() {
var router = this,
user = null;
this.clean();
if(cid){
user = router.userCollection.getByCid(cid);
}
this.currentView = new UserView({
model:user,
router:router
}).render().$el.appendTo($(this.el));
},
clean:function () {
if (this.currentView) {
this.currentView.remove();
this.currentView = null;
}
}
});

•实例化App

 new App('body');
Backbone.history.start();

 •html

<!DOCTYPE html>
<html>
<head>
<title>用户列表以及详细信息</title>
<meta charset="UTF-8"/>
<link rel="stylesheet" type="text/css" href="css/app.css">
<!-- 公共库 -->
<script type="text/javascript" src="js/lib/jquery.js"></script>
<script type="text/javascript" src="js/lib/underscore.js"></script>
<script type="text/javascript" src="js/lib/backbone.js"></script>
<!-- 本地存储库 -->
<script type="text/javascript" src="js/lib/backbone.localStorage.js"></script>
<!--应用库-->
<script type="text/javascript" src="js/app.js"></script>
</head>
<body>
<script type="text/template" id="list-template">
<a href="#add">增加新用户</a>
<ul id="list"> </ul>
</script>
<script type="text/template" id="user-item-template">
<a class="viewUser" href="javascript:;"><%= username %></a>
<a class="removeUser" href="javascript:;">删除</a>
</script>
<script type="text/template" id="user-template">
<p>编号<%= userid %>:</p>
<a href="javascript:;" class="editUser">名字:<%= username %></a>
</script>
<script type="text/template" id="modify-template">
<input type="text" value="<%= username %>">
<a class="add" href="javascript:;"><%= !username ? "增加":"修改" %></a>
</script>
</body>
</html>

(二)backbone - DEMO - user list的更多相关文章

  1. MVVM与Backbone demo

    MVVM https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel

  2. 分享一个非常屌的eazyui二开demo

    eazyui二开Demo非常吊,里面各种非常吊的样例,最喜欢的是 多文件进度条上传,一次可多选,还有流程,还有文本编辑器  非常简洁的 不像一些官网各种复杂的东西.主要为自己保留一份, 在线demo在 ...

  3. (五)backbone - DEMO - 通信录改造之使用requirejs

    DEMO介绍是 DEMO通信录的扩展,使用requirejs模块化整合 大体实现 • model文件 model/contact.js define(function (){ // user cont ...

  4. (四)backbone - DEMO - 通信录

    DEMO介绍 是DEMO - User List 的扩展,增加查询 大体实现 •创建Contact Model var Contact = Backbone.Model.extend({ defaul ...

  5. RobotFrameWork接口报文测试-----(二)demo的升级版

    在上一篇,简单的demo实现了讲xml的数据发送服务器端并取得recvi_buf,然后进行了简单的解析的操作.现在就要解决之前提过的2个问题: 1. 步骤这么多,难道每写一个脚本都要重复一次么? 2. ...

  6. Ace(二)Demo示例

    Client: #include "ace/Log_Msg.h" #include "ace/OS.h" #include "ace/Service_ ...

  7. Vue入门(二)——Demo

    1.在工程目录下创建项目 右键GIT BASH 2.安装lib(建议使用淘宝镜像安装) 3.首页 App.vue <template> <el-container> <e ...

  8. RocketMQ初探(二)之RocketMQ3.26版本搭建(含简单Demo测试案例)

    作为一名程序猿,要敢于直面各种现实,脾气要好,心态要棒,纵使Bug虐我千百遍,我待它如初恋,方法也有千万种,一条路不行,换条路走走,方向对了,只要前行,总会上了罗马的道. Apache4.x最新版本既 ...

  9. 无废话WCF入门教程六[一个简单的Demo]

    一.前言 前面的几个章节介绍了很多理论基础,如:什么是WCF.WCF中的A.B.C.WCF的传输模式.本文从零开始和大家一起写一个小的WCF应用程序Demo. 大多框架的学习都是从增.删.改.查开始来 ...

随机推荐

  1. ios NSKeyedArchiver 保存对象与对象数组

    废话不说,直接上代码 // // CommunityTool.h // SmartCommunity // // Created by chenhuan on 15/9/2. // Copyright ...

  2. JQuery日历插件My97DatePicker日期范围限制

    My97DatePicker是一个非常优秀的日历插件,不仅支持多种调用模式,还支持日期范围限制. 常规的调用比较简单,如下所示: 1 <input class="Wdate" ...

  3. Hadoop学习历程(五、真正的分布式系统搭建)

    之前都是单节点进行的操作与测试,现在进行真正的多节点系统搭建 1. 准备系统与配置 共准备4台机器搭建Hadoop集群.基于CentOS6.2,jdk1.6.0_31,Hadoop2.2.0版本 19 ...

  4. 内核参数优化之2-1 tcp/ip 标志位报文解析

    以下内容纯属虚构,切勿轻易相信! 众所周知,tcp/ip三次握手和四次挥手,均由syn/ack/fin三个标志位报文决定,但是这三个标志位报文,并不是说在构建连接的时候只发送一次的,因为协议不知道网络 ...

  5. docker中运行ASP.NET Core Web API

    在docker中运行ASP.NET Core Web API应用程序 本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过 ...

  6. 被误解的 MVC 和被神化的 MVVM

    被误解的 MVC 和被神化的 MVVM 被误解的 MVC MVC 的历史 MVC,全称是 Model View Controller,是模型 (model)-视图 (view)-控制器 (contro ...

  7. wireshark抓一抓,看是不是另一个机器也企图DHCP

    早上的问题,昨晚四点睡,今早九点半起... 到公司处理此问题,不知道相关性大不大..

  8. BZOJ1270: [BeijingWc2008]雷涛的小猫

    1270: [BeijingWc2008]雷涛的小猫 Time Limit: 50 Sec  Memory Limit: 162 MBSubmit: 836  Solved: 392[Submit][ ...

  9. iOS 9之Advanced Touch Input(高级触摸输入)

    金田 今天要讲的主题是iOS 9高级触摸输入,更准确地讲,是在iOS9上如何减少触摸输入到屏幕显示的延迟程度,此次将分 低延迟渲染(iOS9 渲染性能优化)和 触摸点方案改进 两个方面来介绍. 低延迟 ...

  10. 把第三方的exe程序嵌入C#界面上

    public partial class eTerm_Form : WinFormsUI.Docking.DockContent{public eTerm_Form(){InitializeCompo ...