zoukankan      html  css  js  c++  java
  • [置顶] js模板方法的思路及实现

       在js中如何实现设计模式中的模板方法?

       思路的产生必然要求熟悉js,如何实现?就很简单了,都知道在js中如果定义两个相同名称的方法,前一个方法就会被后一个方法覆盖掉,使用此特点就可以实现模板方法。

      例如在实际的项目中有很多页面操作的步骤基本相同,但局部细节却不一样。例如在我所在的项目中,就有很多展示数据库记录的页面,每个页面都存在读取记录,查询记录,增加删除,修改记录等相同的操作,但对应的后台方法却不一样。

    function ListCommon2() {
        var urlAdd;
        var urlAjax;
        var tableid;
        var titleText="";
        var winid = "#win";
        var columns;
        var toolbars;
        var queryParams;
        var colkey;
        var toolbarsType
        this.initList = function (aurlAdd, aurlAjax, atableid, atitleText, awinid, acolumns, atoolbarsType) {
            urlAdd = aurlAdd;
            urlAjax = aurlAjax;
            if (atableid) {
                tableid = atableid;
            }
            if (atitleText) {
                titleText = atitleText;
            }
            if (atitleText) {
                winid = awinid;
            }
          
            columns = acolumns;
            toolbarsType = atoolbarsType;
        };
        this.initData = function () {
            if (!toolbarsType) {
                toolbars = [{ text: '添加', iconCls: 'icon-add', handler: Add }, '-', { text: '编辑', iconCls: 'icon-edit', handler: this.Edit }
                             	, '-', { text: '删除', iconCls: 'icon-cancel', handler: this.delMsg }
                               ];
            } else {
                toolbars = toolbarsType;
            }      
            queryParams = this.GetqueryParams();
            $(tableid).datagrid({
                url: urlAjax + '?OperationType=list',
                columns: columns,
                toolbar: toolbars,
                idField: colkey,
                pagination: true,
                pageSize: 20,
                sortName: colkey,
                sortOrder: 'desc',
                rownumbers: true, fitColumns: true,
                striped: true,
                method: "post",
                striped: true,
                queryParams: this.GetqueryParams(),
                showFooter: true
                , pageList: [10, 20, 30, 40, 50]
            });
    
            $("#add").click(function (e) {
                Add();
            })
          
            $("#edit").bind('click', { obj: this }, function (event) {
               event.data.obj. Edit();
    
           })
           $("#del").bind('click', { obj: this }, function (event) {
               event.data.obj.delMsg();
           })     
            $("#btnQuery").bind('click', { obj: this }, function (event) {
                var queryParamsnew = event.data.obj.GetqueryParams();
                $(tableid).datagrid('load', queryParamsnew)
            })
        }
        this.GetqueryParams = function () {
            var NameList = this.Getcolsinfo();
            var otherQueryParams = this.GetOtherQueryParams();
            if (!otherQueryParams) {
                return { colkey: colkey, colsinfo: NameList }
            }
            else {
                return otherQueryParams;
            }
        }
    
        this.GetOtherQueryParams = function () {
            return null;
        }
        this.Getcolsinfo = function () {
            var fieldNameList = [];
            if (columns.length > 0) {
                for (var i = 0; i < columns[0].length; i++) {
                    fieldNameList.push(columns[0][i].field);
                }
            }
            else {
                alert("未绑定数据");
            }
            colkey = fieldNameList[fieldNameList.length-1];
            var NameList = fieldNameList.join(",");
            return NameList
        }
        function Add() {
            var _content = '<iframe id="FRMdetail"  frameborder="0"  src=' + urlAdd + ' style="100%;height:100%;" ></iframe>';
            $(winid).dialog({
                 600,
                height: 400,
                modal: true,
                content: _content,
                title: "增加" + titleText,
                draggable: true,
                resizable: true,
                shadow: true,
                minimizable: false
            });
        }
        this.Edit = function (editId) {
            var id; var obj = typeof (editId); 
            if (!editId || obj == "object") {
                var items = $(tableid).datagrid('getSelections');
                var length = items.length;
                if (length == 0) {
                    $.messager.alert('提示', '请选择一条记录然后编辑');
                    return;
                } else if (length > 1) {
                    $.messager.alert('提示', '由于一次只能编辑一条记录,所以只能修改第一条记录');
                    return;
                }
               id = GetId(items[0]);
            }
            else {
                id = editId;
            }
    
            var _content = '<iframe id="FRMdetail"  frameborder="0"  src=' + urlAdd + '?Id=' + id + ' style="100%;height:100%;" ></iframe>';
            $(winid).dialog({
                 600,
                height: 400,
                modal: true,
                content: _content,
                title: "修改" + titleText,
                draggable: true,
                resizable: true,
                shadow: true,
                minimizable: false
            });
        }
        this.windowclose = function () {
            $(winid).window('close');
        }
        this.SaveOkCallback = function () {
            this.windowclose();
            $(tableid).datagrid('reload');
            $(tableid).datagrid('unselectAll');
        }
         this.delMsg = function (delId) {
             var length = 1;
             var id;
             var items; var obj = typeof (delId);
             if (!delId || obj == "object") {
                  items = $(tableid).datagrid('getSelections');
                  length = items.length;
                 if (length == 0) {
                     $.messager.alert('提示', '请至少选择一条记录然后删除');
                     return;
                 }
             }
             else {
                 id = delId;
             }
             var text = '你确认删除' + length + '条记录吗?';
             if (length == 1) {
                 text = '你确认删除该条记录吗?';
             }
             $.messager.confirm('提示', text, function (r) {
                 if (r) {
                     if (!delId) {
                         var idList = [];
                         $.each(items,
                                function (key, value) {
                                    var id = GetId(value); // in case we're changing the key
                                    idList.push(id);
                                });
                         id = idList.join(",");
                     }
                     del(id)
                 }
             });
         }
    
        function del(id) {
            $.ajax({ type: "post",
                url: urlAjax + "?OperationType=del&id=" + id,
                success: function (msg) {
                    var obj = jQuery.parseJSON(msg);
                    if (obj.IsSuccess == true) {
                        $.messager.alert('提示', obj.Msg);               
                        selectcallback();
                    }
                    else {
                        $.messager.alert('提示', obj.Msg);
                    }
                }
            });
        }
    
        function selectcallback() {
            SaveOkCallback();        
        }   
    }
    


    仔细看看就会发现,这段代码就包含了,查询,修改,添加,删除等几乎所有的操作,但由于查询条件传递的参数不同,所以有一个需要重写的方法this.GetOtherQueryParams 

    根据不同的页面重写就可以了。

    例如如下一个页面的重写:

      $(document).ready(function () {
                                     obj = new ListCommon2();
                                    obj.initList(urlAdd, urlAjax, tableid, titleText, winid, columns, '#tb');
                                    obj.GetOtherQueryParams = function () {
                                        var colsinfo = obj.Getcolsinfo();
                                        return { colsinfo: colsinfo, SWV_Performance_fk: $('#SWV_Performance_fk').combobox('getValue'), S_NAME: $("#S_NAME").val(), SQ_NAME: $("#SQ_NAME").val() };
                                    }                             
                                    obj.initData();                                                         
                                })  


    当然也可以不定义方法,此处只调用,例如GetId(items[0]);在此处就没有定义,在具体的页面在具体定义

     <script type="text/javascript">
         function GetId(item) {
                return item.SWV_ID
            }   
         
        </script>


    都可以达到同样的效果。还有一种就是传递一个函数。具体哪种方式最合适,个人认为还是使用模板方法最好。

  • 相关阅读:
    3种方法实现CSS隐藏滚动条并可以滚动内容
    javascript 计算两个整数的百分比值
    使用watch监听路由变化和watch监听对象的实例
    springboot全局捕获异常
    使用 Java 创建聊天客户端-2
    使用 Java 创建聊天客户端-1
    使用 ServerSocket 建立聊天服务器-2
    使用 ServerSocket 建立聊天服务器-1
    ServerSocket
    scheduled定时任务+实例请求数据库
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3209130.html
Copyright © 2011-2022 走看看