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. Python 学习日记(第四周)

    set数据类型 先用一行代码来说明一下 #!/usr/bin/env python s2={} s = {33,12,33,32121} for i in s: print(i) print(type ...

  2. 《VIM-Adventures攻略》 LEVEL 4、5

    本文已转至http://cn.abnerchou.me/2014/03/10/46d23509/ 上一篇文章忘记说明文本编辑器的模式: 所有文本编辑器都至少有两种模式,编辑模式和控制模式.编辑模式就是 ...

  3. jboss-AS目录结构了解(资料摘取)

    Directory Description bin Contains startup, shutdown and other system-specific scripts. Basically al ...

  4. Codeforces 163A Substring and Subsequence

    http://codeforces.com/problemset/problem/163/A?mobile=true 题目大意:给出两个串,问a的连续子串和b的子串(可以不连续)相同的个数. 思路:在 ...

  5. MCS-51单片机实用子程序库

    目前已有若干版本的子程序库公开发表,它们各有特色.本程序库中的开平方算法为快速逼近算法,它能达到牛顿迭代法同样的精度,而速度加快二十倍左右,超过双字节定点除法的速度. 本子程序库对<单片机应用程 ...

  6. win10系统加载ahci驱动的操作方案(Win10之家)

    win10系统使用的过程中很多用户会想要加载ahci驱动,但是大部分用户根本不知道怎么操作加载ahci驱动,这样的话很多用户会遇到一些问题,那如果使用的过程中想要加载ahci驱动的话我们应该怎么操作呢 ...

  7. c#进程间通信(Inter-Process Communication)

    原文:c#进程间通信(Inter-Process Communication) c#进程间通信(IPC, Inter-Process Communication) 接收端: using System; ...

  8. BZOJ1638: [Usaco2007 Mar]Cow Traffic 奶牛交通

    1638: [Usaco2007 Mar]Cow Traffic 奶牛交通 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 571  Solved: 199 ...

  9. NOI2015

    D1T1 并查集. #include<cstdio> #include<cstdlib> #include<iostream> #include<fstrea ...

  10. bzoj1145

    题目:http://www.lydsy.com/JudgeOnline/problem.php?id=1145 神题...... 定义f(abcd)为高度排名为abcd的个数,例如闪电的个数为f(13 ...