Knockout示例:User数据CRUD
模拟数据user.json。
{
"page": 0,
"rows": 0,
"total": 161,
"isSuccess": true,
"validationResult": 0,
"message": "success",
"result": [
{
"Id":"d5e804ed-f428-4842-905e-36635e992242",
"createdBy": "1ad031b6-6843-434c-8241-c05eb06d4b01",
"createdTime": "2019-01-11 11:19:54",
"modifiedBy": "1ad031b6-6843-434c-8241-c05eb06d4b01",
"modifiedTime": "2019-01-11 05:51:40",
"code": "513",
"UserName": "dwd123",
"departmentId": "00f44c5e-8d65-4a1f-9f11-3dae195f86fa"
},
{
"Id":"03d4129c-1613-4e54-bbdf-760a2938d718",
"createdBy": "0290fea5-984e-4a4e-8d98-cd79171db153",
"createdTime": "2019-01-10 04:03:05",
"modifiedBy": "0290fea5-984e-4a4e-8d98-cd79171db153",
"modifiedTime": "2019-01-10 04:03:05",
"code": "512",
"UserName": "tss345",
"departmentId": "03d4129c-1613-4e54-bbdf-760a2938d718"
},
{
"Id":"06d6201c-3385-441c-a372-b156e2aa7f42",
"createdBy": "85dfcc28-c055-41b7-8d81-233be57d80e7",
"createdTime": "2019-01-10 09:31:15",
"modifiedBy": "85dfcc28-c055-41b7-8d81-233be57d80e7",
"modifiedTime": "2019-01-10 09:31:15",
"code": "512",
"UserName": "jojo567",
"departmentId": "03d4129c-1613-4e54-bbdf-760a2938d718"
}
],
"extension": {}
}
userlist.html
<!--查询条件-->
<div class="panel panel-primary">
<div class="panel-heading">
Search
</div>
<!-- 查询 -->
<div class="panel-body">
<div class="form-horizontal" role="form">
<div class="form-group">
<label for="FindUserName" class="col-sm-1 control-label"><strong>UserName:</strong></label>
<div class="col-sm-2">
<input type="text" class="form-control" id="FindUserName" data-bind="value:FindUserName">
</div>
<label for="DepartmentName" class="col-sm-1 control-label"><strong>Department:</strong> </label>
<div class="col-sm-2">
<!-- <select class="form-control" data-bind="options:department, optionsText:'name', optionsValue:'value',optionsCaption: 'Choose...',value:selectitemvalue"></select> -->
<select class="form-control" data-bind="options:department,optionsText:'name', optionsValue:'value',optionsCaption: 'Choose...',value : FindDepartment"></select>
</div>
<button type="button" class="btn btn-default col-sm-1" data-bind="click:searchUser">
<span class="glyphicon glyphicon-search" aria-hidden="true"></span>Search
</button>
</div>
</div>
</div>
<!--操作按钮-->
<div id="toolbar" class="btn-group">
<button id="btn_add" type="button" class="btn btn-default" data-bind="click:addUser">
<span class="glyphicon glyphicon-plus" aria-hidden="true">Add</span>
</button>
<button id="btn_edit" type="button" class="btn btn-default" data-bind="click:$root.editUser">
<span class="glyphicon glyphicon-pencil" aria-hidden="true">Edit</span>
</button>
<button id="btn_delete" type="button" class="btn btn-default" data-bind="click:$root.delUser">
<span class="glyphicon glyphicon-remove" aria-hidden="true">Delete</span>
</button>
</div>
<!--数据绑定-->
<div class="div-table">
<table class="table table-bordered">
<thead>
<tr>
<th width="30px"><input type="checkbox" data-bind="checked:selectAll,click:checkedAll"></th>
<th width="200px">ID</th>
<th width="100px">UserName</th>
<th>Department</th>
<th width="150px">CreateBy</th>
<th width="150px">CreateTime</th>
<th width="200px">ModifiedBy</th>
<th width="150px">ModifiedTime</th>
</tr>
</thead>
<tbody data-bind="foreach: list">
<tr>
<td><input type="checkbox" data-bind="value:Id,checked:$parent.selectOne,click:$parent.checkedOne"></td>
<td><span data-bind="text: Id"></span></td>
<td><span data-bind="text: UserName"></span></td>
<td><span data-bind="text: departmentId"></span></td>
<td><span data-bind="text: createdBy"></span></td>
<td><span data-bind="text: createdTime"></span></td>
<td><span data-bind="text: modifiedBy"></span></td>
<td><span data-bind="text: modifiedTime"></span></td>
</tr>
</tbody>
</table>
</div>
<!-- 新增、修改弹窗 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="width:50%">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="myModalLabel">
User Manager
</h4>
</div>
<div class="modal-body">
<div class="form-group col-sm-6">
<label for="Id" class="control-label">Id:</label>
<input type="text" class="form-control" data-bind="value: Model().Id" id="Id" disabled="disabled">
</div>
<div class="form-group col-sm-6">
<label for="departmentId" class="control-label">Department Name:</label>
<select id="departmentId" class="form-control" data-bind="options:department,optionsText:'name', optionsValue:'value',optionsCaption: 'Choose...',value:Model().departmentId"></select>
</div>
<div class="form-group col-sm-6">
<label for="UserName" class="control-label">User Name:</label>
<input type="text" class="form-control" data-bind="value: Model().UserName" id="UserName" >
</div>
<div class="form-group col-sm-6">
<label for="dt_id" class=" control-label">Age:</label>
<input type="text" class="form-control" data-bind="value:Model().Age" id="Age">
</div>
<div class="form-group col-sm-6">
<label for="createdBy" class="control-label">Created By:</label>
<input type="text" class="form-control" data-bind="value:Model().createdBy" id="createdBy">
</div>
<div class="form-group col-sm-6">
<label for="createdTime" class="control-label">Created Time:</label>
<input type="text" class="form-control" data-bind="value:Model().createdTime" id="createdTime" disabled="disabled">
</div>
<div class="form-group col-sm-6">
<label for="modifiedBy" class="control-label">Modited By:</label>
<input type="text" class="form-control" data-bind="value:Model().modifiedBy" id="modifiedBy">
</div>
<div class="form-group col-sm-6">
<label for="modifiedTime" class="control-label">Modited Time:</label>
<input type="text" class="form-control" data-bind="value:Model().modifiedTime" id="modifiedTime" disabled="disabled">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close
</button>
<button type="button" class="btn btn-primary" data-bind="click:$root.saveUser">
Save
</button>
</div>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
</div>
userlist.js
define([
"plugins/router",
"durandal/app",
"plugins/http",
"knockout",
"config"
], function(router, app, http, ko, config) {
// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt) {
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"H+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
S: this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(
RegExp.$1,
(this.getFullYear() + "").substr(4 - RegExp.$1.length)
);
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1
? o[k]
: ("00" + o[k]).substr(("" + o[k]).length)
);
return fmt;
};
var tempAllList = []; //全选时,临时总数组
var viewModel = function() {
var self = this;
self.operate = "add";
self.name = ko.observable();
self.department = ko.observableArray([]);
self.list = ko.observableArray([]);
self.selectAll = ko.observable();
self.selectOne = ko.observableArray([]); //单选时,保存的数组
self.Model = ko.observable([]); //当前行
self.FindUserName = ko.observable();
self.FindDepartment = ko.observable();
self.listCopy = ko.observableArray([]);
GetDepartment();
GetList();
//1.获取列表
function GetList() {
tempAllList = [];
if (self.list != null) {
http.get("app/components/datatest/user.json").success(function(data) {
// console.log("data:");
// console.log(data);
self.list(data.result);
//给selectOne 赋值Id的List
for (var i = 0; i < data.result.length; i++) {
//self.selectOne.push(data.result[i].Id);//绑定全选数组
tempAllList.push(data.result[i].Id); //全选时,临时总数组赋值
}
});
} else {
for (var i = 0; i < self.list.length; i++) {
//self.selectOne.push(data.result[i].Id);//绑定全选数组
tempAllList.push(self.list[i].Id); //全选时,临时总数组赋值
}
}
}
//2.查询部门
function GetDepartment() {
var parms = {
table: "Department",
method: "read",
params: "{getAction:'GetDepartmentInfoList',Page:'1',PageSize:'20'}"
};
http
.post(config.apiUrl, parms, "application/json; charset=utf-8")
.success(function(data) {
for (var i = 0; i < data.result.length; i++) {
self.department.push(
new selectOptions(data.result[i].name, data.result[i].id)
);
}
})
.fail(function(result) {
app.showMessage("There is an error with connection !");
});
}
//3.全选事件
self.checkedAll = function() {
var select = self.selectAll();
console.log(tempAllList);
if (!select) {
self.selectOne.removeAll(); //取消所有勾选
} else {
self.selectOne(tempAllList.slice()); //勾选全部。 tempAllList.slice() 复制一个数组
}
return true;
};
//单选事件
self.checkedOne = function() {
//console.log(self.selectOne()); //选择数
//console.log("list:" + self.list().length); //总数
if (self.selectOne().length == self.list().length) {
self.selectAll(true);
} else {
self.selectAll(false);
}
// console.log(self.Model());
// console.log(self.selectOne());
return true;
};
/**
* 查询按钮
*/
self.searchUser = function () {
// console.log('FindUserName:'+ self.FindUserName());
// console.log('FindDepartment:'+self.FindDepartment());
if (self.listCopy().length == 0) {
self.listCopy(self.list());
}
console.info("self.listCopy().length:"+self.listCopy().length)
console.info("self.list().length:"+self.list().length)
var list = self.listCopy().slice();
// 过滤查询条件
var filterArr = []; //条件
list.forEach(x => {
if (!(self.FindUserName() == undefined)) {
filterArr.push(x => x.UserName.includes(self.FindUserName()));
}
if(!(self.FindDepartment() == undefined)){
//查找到数据
filterArr.push(x => x.departmentId == (self.FindDepartment()));
}
});
//多条件组合查询。
self.list(list);
filterArr.forEach(x => {
self.list(self.list().filter(x));
});
//恢复默认
if((self.FindDepartment() == "" || self.FindDepartment() == null || self.FindDepartment() == undefined)&&
(self.FindUserName() == "" || self.FindUserName() == null || self.FindUserName() == undefined) ){
self.list(self.listCopy());
}
}
/**
* 新增按钮
*/
self.addUser = function(data) {
var arr = {
Id: "",
createdBy: "",
createdTime: "",
modifiedBy: "",
modifiedTime: "",
code: "777777777",
UserName: "",
departmentId: ""
};
arr.createdTime = arr.modifiedTime = new Date().Format(
"yyyy-MM-dd HH:mm"
);
self.Model(ko.toJS(arr));
console.log(self.Model());
self.operate = "add";
$("#myModal").modal("show");
};
/**
* 修改按钮
*/
self.editUser = function(omodel) {
if (self.selectOne().length == 0) {
app.showMessage("Please select at least one row of data", "Hint");
return false;
}
if (self.selectOne().length > 1) {
app.showMessage("Only one row of data can be edited", "Hint");
return false;
}
//勾选单选时,存储 self.Model
for (var i = 0; i < self.list().length; i++) {
if (self.list()[i].Id == self.selectOne()) {
self.Model(self.list()[i]);
}
}
self.operate = "edit";
// console.log("当前行:");
// console.info(self.Model());
$("#myModal").modal("show");
};
/**
* 删除按钮
*/
self.delUser = function() {
app
.showMessage(
"Are you sure you want to delete " +
self.selectOne().length +
" row??",
"Hint",
["Yes", "No"]
)
.then(function(isOK) {
if (isOK == "Yes") {
var list = self.list().slice();
var selectOne = self.selectOne().slice();
for (var i = 0; i < list.length; i++) {
for (var y = 0; y < selectOne.length; y++) {
//console.log(list[i].Id + ":" + selectOne[y]);
if (list[i].Id == selectOne[y]) {
self.selectOne.remove(list[i].Id); //单选总数据
tempAllList.find(p => (p == list[i].Id)); //全选总数据
self.list.remove(list[i]);
}
}
}
}
});
};
/**
* 保存按钮
*/
self.saveUser = function(data) {
var oData = data.list();
app
.showMessage(
"You have unsaved data. Are you sure you want to save?",
"Hint",
["Yes", "No"]
)
.then(function(isOK) {
if (isOK == "Yes") {
if (self.operate == "edit") {
console.log("edit");
//更新列表 self.list
self.list([]);
self.list(oData.slice());
// console.log('self.list():');
// console.log(self.list());
//GetList();
} else {
console.log("add");
self.Model().Id = guid();
tempAllList.push(self.Model().Id); //添加到全选时的临时总数组
self.list.push(self.Model());
}
}
$("#myModal").modal("hide");
});
}.bind(self);
};
return viewModel;
//option对象
function selectOptions(name, value) {
this.name = name;
this.value = value;
}
//生产guid
function guid() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
var r = (Math.random() * 16) | 0,
v = c == "x" ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
});
Knockout示例:User数据CRUD的更多相关文章
- knockout示例
最近项目需要用到knockout js,有关knockout的介绍网上已经很多很多了,但是很少有比较全面的示例,于是乎我就自己做了一个小demo,已备以后查阅.knockout经常和knockout. ...
- 黑马MySQL数据库学习day02 表数据CRUD 约束CRUD
/* 基础查询练习: 1.字段列表查询 当查询全部字段时,一种简便方式,使用*代替全部字段(企业中不推荐使用) 2.去除重复行 DISTINCT,注意修饰的是行,也就是整个字段列表,而不是单个字段. ...
- Spring Data Redis入门示例:数据序列化 (四)
概述 RedisTemplate默认使用的是基于JDK的序列化器,所以存储在Redis的数据如果不经过相应的反序列化,看到的结果是这个样子的: 可以看到,出现了乱码,在程序层面上,不会影响程序的运行, ...
- 分布式 PostgreSQL 集群(Citus)官方示例 - 时间序列数据
在时间序列工作负载中,应用程序(例如一些实时应用程序查询最近的信息,同时归档旧信息. https://docs.citusdata.com/en/v10.2/sharding/data_modelin ...
- smartjs - DataManager 场景示例分析 - 数据懒加载
发一张policy的参数图设置图: 场景1 - 数据的懒加载/延迟加载 在很多时候,为了提高网页的加载速度,减少不必要的开销,会将页面的数据拆分成几个部分,首先加载呈现可视区域内的数据,然后剩下来的会 ...
- Asp .net core api+Entity Framework core 实现数据CRUD数据库中(附Git地址)
最近在学dotNetCore 所以尝试了一下api 这个功能 不多说了大致实现如下 1.用vs2017建立一个Asp.net Core Web 应用程序 在弹出的对话框中选择 Web API 项目名 ...
- php连接mysql,数据CRUD操作
插入数据 <?php $name = $_GET['username']; $sex = $_GET['sex']; $hobby = $_GET['hobby']; $address = $_ ...
- 小爬爬4.协程基本用法&&多任务异步协程爬虫示例(大数据量)
1.测试学习 (2)单线程: from time import sleep import time def request(url): print('正在请求:',url) sleep() print ...
- MeteoInfoLab脚本示例:数据投影-FLEXPART
FLEXPART是一个类似HYSPLIT的扩散模式,它输出的netcdf文件参照了WRF,可惜全局属性没有写全,比如只有一个投影名称(例如Lambert),没有相关的投影参数:中央经度,标准纬度等等. ...
随机推荐
- pyinstaller 打包exe可执行文件
Python打包EXE方法之一 一.安装Pyinstaller 1.安装pywin32 下载安装文件:查找到跟自己适用的python版本及window系统版本匹配的pywin32,下载后安装 使用pi ...
- python3+selenium入门05-元素操作及常用方法
学习了元素定位之后,来看一些元素的操作,还有一些常用的方法 clear()清空输入框内容 click()点击 send_keys()键盘输入 import time from selenium imp ...
- Codeforces 914D - Bash and a Tough Math Puzzle 线段树,区间GCD
题意: 两个操作, 单点修改 询问一段区间是否能在至多一次修改后,使得区间$GCD$等于$X$ 题解: 正确思路; 线段树维护区间$GCD$,查询$GCD$的时候记录一共访问了多少个$GCD$不被X整 ...
- Cassandra索引详解
转自: https://www.cnblogs.com/bonelee/p/6278943.html 1.什么是二级索引? 我们前面已经介绍过Cassandra之中有各种Key,比如Primary K ...
- Android视频录制命令screenrecord
不管是教学,还是为了演示,如果能将Android手机(或平板)的屏幕录制成视频文件,那是一件非常酷的事(iOS8已经提供了这一功能,能通过OS X直接在Mac上录制iPad.iPhone的屏幕,win ...
- [转载]RabbitMQ消息可靠性分析
有很多人问过我这么一类问题:RabbitMQ如何确保消息可靠?很多时候,笔者的回答都是:说来话长的事情何来长话短说.的确,要确保消息可靠不只是单单几句就能够叙述明白的,包括Kafka也是如此.可靠并不 ...
- 使用Gitblit 在Windows上部署Git Server
Windows平台下Git服务器搭建 首先要下载Java JDK,安装完成后设置环境变量,先把java环境配好,接下来才是下面的gitblit.关于java环境配置请看上一篇文章 gitblit下载 ...
- python----动态规划
不能放弃治疗,每天都要进步!! 什么时候使用动态规划呢? 1. 求一个问题的最优解 2. 大问题可以分解为子问题,子问题还有重叠的更小的子问题 3. 整体问题最优解取决于子问题的最优解(状态转移方程) ...
- Vue项目构建开发笔记(vue-lic3.0构建的)
1.router.js里面 { path: '/about', name: 'about', // route level code-splitting // this generates a sep ...
- js获取参数函数