Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 07.JS代码重构

原文地址:http://www.work100.net/training/monolithic-project-iot-cloud-admin-manager-js.html
更多教程:光束云 - 免费课程

JS代码重构

序号 文内章节 视频
1 概述 -
2 Select2控件初始化通用模块 -
3 消息提示通用模块 -
4 表单验证通用模块 -
5 模态对话框通用模块 -
6 各视图文件代码修改 -
7 实例源码 -

请参照如上章节导航进行阅读

1.概述

我们进行视图页面编码时会编写自己的JS脚本,同时也会使用第三方的UI控件,其实这些JS脚本及UI控件大多数都是通用的,都可以提炼为公用模块,接下来我们将完成这些提炼工作。

2.Select2控件初始化通用模块

页面中用到 select 控件时,需要引入 Bootstrap 的样式效果,要达到效果,则需在页面加载时执行如下代码:

//Initialize Select2 Elements
$('.select2').select2();

//Initialize Select2 Elements
$('.select2bs4').select2({
    theme: 'bootstrap4'
});

下面我们将如上代码提取到一个公用的 js 文件中。

首先,在 /webapp/static/assets/js/ 目录下新建一个文件 select2-utils.js,代码如下:

let Select2 = function() {

    let handleInitSelect2 = function() {
        //Initialize Select2 Elements
        $('.select2').select2();

        //Initialize Select2 Elements
        $('.select2bs4').select2({
            theme: 'bootstrap4'
        });
    }

    return {
        init: function() {
            handleInitSelect2();
        }
    }
}();

$(function() {
    Select2.init();
});

然后,删除原有页面中的自定义 js 代码,用引入文件的方式代替,代码如下:

<script src="/static/assets/js/select2-utils.js"></script>

3.消息提示通用模块

对于页面中用到的消息提示,比如 操作成功操作失败 ,我们是使用如下代码实现的:

成功消息

const Toast = Swal.mixin({
    toast: true,
    position: 'top',
    showConfirmButton: false,
    timer: 2000,
    timerProgressBar: true,
    onOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer)
        toast.addEventListener('mouseleave', Swal.resumeTimer)
    }
})

Toast.fire({
    type: 'success',
    title: '操作成功'
})

失败消息

const Toast = Swal.mixin({
    toast: true,
    position: 'top',
    showConfirmButton: false,
    timer: 2000,
    timerProgressBar: true,
    onOpen: (toast) => {
        toast.addEventListener('mouseenter', Swal.stopTimer)
        toast.addEventListener('mouseleave', Swal.resumeTimer)
    }
})

Toast.fire({
    type: 'error',
    title: '操作错误'
})

提取公用

我们将如上方法提取到一个公用的 js 文件中,在 /webapp/static/assets/js/ 目录下新建一个文件 message-utils.js,代码如下:

let Message = function() {

    const toast = Swal.mixin({
        toast: true,
        position: 'top',
        showConfirmButton: false,
        timer: 2000,
        timerProgressBar: true
    })

    /**
     * 显示成功信息
     */
    let handleShowSuccess = function(title) {
        toast.fire({
            type: 'success',
            title: title
        })
    }

    /**
     * 显示失败信息
     */
    let handleShowFail = function(title) {
        toast.fire({
            type: 'error',
            title: title
        })
    }

    return {
        showSuccess: function(title) {
            handleShowSuccess(title);
        },

        showFail: function(title) {
            handleShowFail(title);
        }
    }
}();

使用

首先,删除原有页面中的自定义 js 代码,用引入文件的方式代替,代码如下:

<script src="/static/assets/js/message-utils.js"></script>

然后,使用消息提示,如:

if (${baseResult.status != null && baseResult.status != 200}) {
    Message.showFail('${baseResult.message}');
}

4.表单验证通用模块

在对表单进行验证时,我们使用如下的 js 代码:

$("#form").validate({
    rules: {
        userName: {
            required: true,
            minlength: 4,
            maxlength: 20
        },
        password: {
            required: true,
            minlength: 6,
            maxlength: 20
        },
        roles: {
            required: true,
            minlength: 1,
            maxlength: 3
        }
    },
    messages: {
        userName: {
            required: " 请输入用户名",
            minlength: " 用户名不能小于4位",
            maxlength: " 用户名不能大于于20位"
        },
        password: {
            required: " 请输入密码",
            minlength: " 密码不能小于6位",
            maxlength: " 密码不能大于于20位"
        },
        roles: {
            required: " 请选择角色",
            minlength: " 至少选择1个角色",
            maxlength: " 至多选择3个角色"
        }
    },
    errorElement: 'span',
    errorPlacement: function(error, element) {
        error.addClass('invalid-feedback');
        element.closest('.form-group').children('label').append(error);
    },
    highlight: function(element, errorClass, validClass) {
        $(element).addClass('is-invalid');
    },
    unhighlight: function(element, errorClass, validClass) {
        $(element).removeClass('is-invalid');
    }
});

提取公用

接下来我们将表单验证代码提取到一个公用文件 form-validate-utils.js,代码如下:

let FormValidate = function() {

    let form = $('#form');

    /**
     * 处理验证
     */
    let handleValidate = function(formId, rules, messages) {
        if (formId != '' || formId != null) {
            form = $('#' + formId);
        }

        form.validate({
            rules: rules,
            messages: messages,
            errorElement: 'span',
            errorPlacement: function(error, element) {
                error.addClass('invalid-feedback');
                element.closest('.form-group').children('label').append(error);
            },
            highlight: function(element, errorClass, validClass) {
                $(element).addClass('is-invalid');
            },
            unhighlight: function(element, errorClass, validClass) {
                $(element).removeClass('is-invalid');
            }
        });
    }

    return {
        validate: function(formId, rules, messages) {
            handleValidate(formId, rules, messages);
        }
    }
}();

使用

首先,删除原有页面中的自定义 js 代码,用引入文件的方式代替,代码如下:

<script src="/static/assets/js/form-validate-utils.js"></script>

然后,使用表单验证,如:

FormValidate.validate(
    'form',
    {
        userName: {
            required: true,
            minlength: 4,
            maxlength: 20
        },
        password: {
            required: true,
            minlength: 6,
            maxlength: 20
        },
        roles: {
            required: true,
            minlength: 1,
            maxlength: 3
        }
    },
    {
        userName: {
            required: " 请输入用户名",
            minlength: " 用户名不能小于4位",
            maxlength: " 用户名不能大于于20位"
        },
        password: {
            required: " 请输入密码",
            minlength: " 密码不能小于6位",
            maxlength: " 密码不能大于于20位"
        },
        roles: {
            required: " 请选择角色",
            minlength: " 至少选择1个角色",
            maxlength: " 至多选择3个角色"
        }
    }
);

5.模态对话框通用模块

提取公用

在执行删除动作时,我们有个确认提示框,下面我们将其功能提取到公用的 modal-dialog-utils.js 文件中,代码如下:

let ModalDialog = function() {

    /**
     * 弹出确认对话框
     * @param modalId
     * @param title
     * @param message
     * @param callback
     * @param callback_params
     */
    let handleShowConfirm = function(modalId, title, message, callback, callback_params) {
        let modal = $('<div id="' + modalId + '"></div>');

        let modalDialog = $('<div></div>');
        let modalContent = $('<div></div>');
        let modalHeader = $('<div></div>');
        let modalBody = $('<div></div>');
        let modalFooter = $('<div></div>');

        let html;

        // modal-header html
        modalHeader.attr('class', 'modal-header');
        html = '';
        html = html + '<h4 class="modal-title">' + title + '</h4>';
        html = html + '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
        html = html + '  <span aria-hidden="true">&times;</span>';
        html = html + '</button>';
        modalHeader.html(html)

        // modal-body html
        modalBody.attr('class', 'modal-body');
        html = '';
        html = html + '<p>' + message + '</p>';
        modalBody.html(html);

        // modal-footer html
        let btnCancel = $('<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>');
        let btnOk = $('<button type="button" class="btn btn-primary">确定</button>');
        btnOk.on('click', function() {
            modal.modal('hide');
            callback(callback_params);
        });

        modalFooter.attr('class', 'modal-footer');
        modalFooter.append(btnCancel);
        modalFooter.append(btnOk);

        // modal-content
        modalContent.attr('class', 'modal-content');
        modalContent.append(modalHeader);
        modalContent.append(modalBody);
        modalContent.append(modalFooter);

        // modal-dialog
        modalDialog.attr('class', 'modal-dialog');
        modalDialog.append(modalContent);

        modal.attr('class', 'modal fade');
        modal.append(modalDialog);
        modal.modal('show');

        $(modal).on('hidden.bs.modal', function(e) {
            modal.remove();
        })

        $("body").append(modal);
    }

    return {
        showConfirm: function(modalId, title, message, callback, callback_params) {
            handleShowConfirm(modalId, title, message, callback, callback_params);
        }
    }
}();

使用

首先,删除页面中的 modal 定义标签,同时删除原有页面中的自定义 js 代码,用引入文件的方式代替,代码如下:

<script src="/static/assets/js/modal-dialog-utils.js"></script>

然后,重新定义删除功能 JS 脚本代码,如下:

// 单个删除
function singleDelete(userKey) {
    ModalDialog.showConfirm('single-delete-confirm', '操作确认', '删除后数据不可恢复,您确认要操作吗?', singleDelete_callback, userKey);
}

function singleDelete_callback(userKey) {
    location.href = '/auth/manager/delete/' + userKey;
}

最后,删除按钮 onclick 事件增加如下代码:

<button type="button" class="btn btn-danger btn-sm" onclick="singleDelete('${authManager.userKey}');"><i class="fas fa-trash"></i></button>

6.各视图文件代码修改

我们已经提取了如下几个公用 js 文件:

  • /static/assets/js/select2-utils.js
  • /static/assets/js/message-utils.js
  • /static/assets/js/modal-dialog-utils.js

接下来需要将所有使用相关功能的视图文件进行修改,我们以 managere_add.jsp 视图文件为例,修改后的代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
    <title>新增账户 - 后台账户 | IoT-Admin</title>
    <jsp:include page="../includes/resources_head.jsp" />
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">

    <jsp:include page="../includes/layout_header.jsp" />

    <jsp:include page="../includes/layout_left.jsp" />

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0 text-dark">新增账户</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#">后台账户</a></li>
                            <li class="breadcrumb-item active">新增账户</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col">
                        <div class="card card-gray">
                            <!-- form start -->
                            <form:form action="/auth/manager/add" id="form" method="post" modelAttribute="authManager">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="userName">用户名</label>
                                                <form:input path="userName" cssClass="form-control" placeholder="请输入用户名" />
                                            </div>
                                            <div class="form-group">
                                                <label for="password">密码</label>
                                                <form:password path="password" cssClass="form-control" placeholder="请输入密码" />
                                            </div>
                                            <div class="form-group">
                                                <label for="status">状态</label>
                                                <form:select path="status" cssClass="form-control select2" style="width: 100%;">
                                                    <option value="0" selected="selected">未激活</option>
                                                    <option value="1">激活</option>
                                                    <option value="2">锁定</option>
                                                    <option value="3">删除</option>
                                                </form:select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="roles">角色</label>
                                                <form:select path="roles" cssClass="select2" multiple="multiple" data-placeholder="请选择角色" style="width: 100%;">
                                                    <option value="admin" ${authManager.roles.contains("admin")?"selected":""}>
                                                        admin
                                                    </option>
                                                    <option value="editor" ${authManager.roles.contains("editor")?"selected":""}>
                                                        editor
                                                    </option>
                                                </form:select>
                                            </div>
                                            <div class="form-group">
                                                <label for="superuser">是否超级用户</label>
                                                <form:select path="superuser" cssClass="form-control select2" style="width: 100%;">
                                                    <option value="0" selected="selected">否</option>
                                                    <option value="1">是</option>
                                                </form:select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <!-- /.card-body -->

                                <div class="card-footer">
                                    <button type="submit" class="btn btn-primary">保存</button>
                                    <a href="/auth/manager/list" type="button" class="btn btn-default">返回列表</a>
                                </div>
                            </form:form>
                        </div>
                        <!-- /.card -->
                    </div>
                </div>
            </div>
            <!-- /.container-fluid -->
        </div>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->

    <jsp:include page="../includes/layout_footer.jsp" />
</div>
<!-- ./wrapper -->
<jsp:include page="../includes/resources_body.jsp" />

<script>
$(function() {
    if (${baseResult.status != null && baseResult.status != 200}) {
        Message.showFail('${baseResult.message}');
    }

    FormValidate.validate(
        'form',
        {
            userName: {
                required: true,
                minlength: 4,
                maxlength: 20
            },
            password: {
                required: true,
                minlength: 6,
                maxlength: 20
            },
            roles: {
                required: true,
                minlength: 1,
                maxlength: 3
            }
        },
        {
            userName: {
                required: " 请输入用户名",
                minlength: " 用户名不能小于4位",
                maxlength: " 用户名不能大于于20位"
            },
            password: {
                required: " 请输入密码",
                minlength: " 密码不能小于6位",
                maxlength: " 密码不能大于于20位"
            },
            roles: {
                required: " 请选择角色",
                minlength: " 至少选择1个角色",
                maxlength: " 至多选择3个角色"
            }
        }
    );
})
</script>
<script src="/static/assets/js/select2-utils.js"></script>
<script src="/static/assets/js/message-utils.js"></script>
<script src="/static/assets/js/form-validate-utils.js"></script>
</body>
</html>

其它视图页面的代码修改,请自己完成。

7.实例源码

实例源码已经托管到如下地址:


上一篇:搜索功能

上一篇:批量删除


如果对课程内容感兴趣,可以扫码关注我们的 公众号QQ群,及时关注我们的课程更新

Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 07.JS代码重构
Java单体应用 - 项目实战(后台) - 03.后台账户管理 - 07.JS代码重构

上一篇:iphone-Cocos2D游戏开发


下一篇:[PHP] Laravel 5.1 实现第三方登录认证