冗余的javascript代码太多了

时间:2012-07-23 06:56:38

标签: c# javascript asp.net

在我的asp.net页面上,我需要控制Dirty控件。我在javascript方面不是很好,所以我在互联网上找到了一个解决方案:

<script type="text/javascript" language="javascript">
    //Demo of completely client side dirty flag.

    function setDirty() {
        document.body.onbeforeunload = showMessage;
        //debugger;
        document.getElementById("DirtyLabel").className = "show";
    }

    function clearDirty() {
        document.body.onbeforeunload = "";
        document.getElementById("DirtyLabel").className = "hide";
    }


    function showMessage() {
        return ""
    }

    function setControlChange() {
        if (typeof (event.srcElement) != 'undefined') {
            event.srcElement.onchange = setDirty;
        }
    }

    document.body.onclick = setControlChange;
    document.body.onkeyup = setControlChange;

    window.onunload = function (sender, eventArgs) {
        if (window.opener != null) {
            window.opener.ClearBlocker();

            if (window.opener.TempClientReturnFunction != null)
                window.opener.TempClientReturnFunction = window.opener.ReturnFunction;
        }
    }
</script>

但如果我有7个页面需要控制Dirty Controls,它将是太多的冗余代码。有没有办法从我可以调用函数的地方创建一些类/库,或者甚至可能有更聪明的方法呢?

2 个答案:

答案 0 :(得分:1)

如前所述,将代码放入单独的文件中,然后包含在需要它的每个页面上。

您可能想要考虑的其他事情是采用“模块”模式,从而将不超过一个成员放入javascript全局命名空间。

模块化,您的代码看起来像这样:

var DIRTY_CONTROL = (function(){ //module pattern
    // *** Private members ***
    var dirtyLabelId = "DirtyLabel";
    var showMessage = function() {
        return "";
    };
    var setDirty = function(id) {
        id = id || dirtyLabelId;
        document.body.onbeforeunload = showMessage;
        //debugger;
        document.getElementById(id).className = "show";
    }
    var clearDirty = function clearDirty(id) {
        id = id || dirtyLabelId;
        document.body.onbeforeunload = "";
        document.getElementById(id).className = "hide";
    };
    var setControlChange = function(e) {
        e = e || window.event;
        var target = e.target || e.srcElement;
        target.onchange = setDirty;
    };
    var init = function() {
        document.body.onclick = document.body.onkeyup = setControlChange;
        window.onunload = function() {
            if (window.opener) {
                if (window.opener.ClearBlocker) {
                    window.opener.ClearBlocker();
                }
                if (window.opener.ReturnFunction) {
                    window.opener.TempClientReturnFunction = window.opener.ReturnFunction;
                }
            }
        };
    };
    // *** Public members ***
    //Expose private members here, as required.
    return {
        clearDirty: clearDirty,
        setDirty: setDirty,
        init: init
    };
})();

未测试

按照惯例,模块的名称大写。

按如下方式调用公共函数:

DIRTY_CONTROL.init();

DIRTY_CONTROL.clearDirty();

答案 1 :(得分:0)

将该JS块放入像Dirty.js这样的JS文件中,然后在要使用它的每个页面上使用以下代码。

<script src="Dirty.js"></script>

您可以在标签之间或身体末端添加它,具体取决于您何时需要实际调用它。