zoukankan      html  css  js  c++  java
  • 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="50%">
            <div class="modal-content">
    
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </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);
        });
      }
    });
    
    
  • 相关阅读:
    JAVA-初步认识-第九章-抽象类-特点
    JAVA-初步认识-第九章-抽象类-概述
    JAVA-初步认识-第九章-面向对象-final关键字
    JAVA-初步认识-第九章-继承-子父类中的构造函数-子类的实例化过程-内存图解
    JAVA-初步认识-第九章-继承-子父类中的构造函数-子类的实例化过程-细节
    JAVA-初步认识-第九章-继承-子父类中的构造函数-子类的实例化过程
    JAVA-初步认识-第八章-继承-子父类中成员变量的特点-覆盖的应用
    JAVA-初步认识-第八章-继承-子父类中成员函数特点-覆盖
    JAVA-初步认识-第八章-继承-子父类中成员变量的内存图解
    JAVA-初步认识-第八章-继承-子父类中成员变量的特点
  • 原文地址:https://www.cnblogs.com/tangge/p/10310466.html
Copyright © 2011-2022 走看看