Home > Web Front-end > JS Tutorial > Develop a complete JavaScript component

Develop a complete JavaScript component

黄舟
Release: 2017-02-25 13:27:49
Original
1526 people have browsed it

As a developer, everyone should know that there are some built-in controls in the browser: Alert, Confirm, etc. However, these controls usually have different shapes according to different browser manufacturers, and the visual effects are often not up to par. UI designer requirements. More importantly, the style of such built-in controls is difficult to unify with the design styles of various Internet products with different styles. Therefore, excellent front-end developers develop their own personalized controls to replace these built-in browser controls. Of course, there are already countless excellent components of this type on the Internet. The purpose of writing this article is not to explain how excellent the component I developed is, nor to show off. I just hope that in this way, I can interact with more Many developers communicate with each other, learn from each other, and make progress together. Okay, without further ado, let’s get down to business.

Function introduction

  • Replace the Alert and Confirm controls that come with the browser

  • Customized interface style

  • The usage method is basically the same as the built-in control

Effect preview

1. Alert control

 2. Confirm control

 3. Complete code, online preview (see bottom, compressed package download is provided)

Development process

 1. Component structure design

First, let’s take a look at the basic usage of built-in components:

 alert("内置Alert控件");
 if (confirm("关闭内置Confirm控件?")) {
     alert("True");
 } else {
     alert("False");
 }
Copy after login

In order to ensure that our components The usage is consistent with the built-in controls, so we must consider overriding the built-in controls. Taking into account the unified style of component development, ease of use, easy maintenance, and object-oriented features, I plan to use the customized alert and confirm methods as instance methods of a class (Winpop), and finally use the instance methods to override the system's built-in controls. method. In order to achieve the goal, my basic approach is as follows:

var obj = new Winpop(); // 创建一个Winpop的实例对象
// 覆盖alert控件
window.alert = function(str) {
    obj.alert.call(obj, str);
};
// 覆盖confirm控件
window.confirm = function(str, cb) {
    obj.confirm.call(obj, str, cb);
};
Copy after login

It should be noted that since the built-in controls of the browser can prevent other behaviors of the browser, our custom components do not have this ability. To be as unified as possible, as you can see in the preview, we use a full-screen semi-transparent mask layer when popping up the custom component. It is precisely because of the above reasons that some subtle adjustments have been made to the way the confirm component is used, from the built-in method of returning a Boolean value to the method of using a callback function to ensure that "OK" and "Cancel" can be added correctly. logic. Therefore, the use of custom components becomes the following form:

alert("自定义Alert组件");
confirm("关闭自定义Confirm组件?", function(flag){
    if (flag) {
        alert("True");
    } else {
        alert("False");
    }
});
Copy after login

 2. Component code design

Before formally introducing the code of the Winpop component, Let’s first take a look at the basic structure of a Javascript component:

(function(window, undefined) {
    function JsClassName(cfg) {
        var config = cfg || {};
        this.get = function(n) {
            return config[n];
        }
        this.set = function(n, v) {
            config[n] = v;
        }
        this.init();
    }
    JsClassName.prototype = {
        init: function(){},
        otherMethod: function(){}
    };
    window.JsClassName = window.JsClassName || JsClassName;
})(window);
Copy after login

Use a self-executing anonymous function to wrap our component code to reduce global pollution as much as possible, and finally attach our class to the global For window objects, this is a recommended approach.

The get and set methods in the constructor are not necessary. It is just the author's personal habit. I feel that writing it this way can unify the calling methods of caching and reading the configuration parameters and other components' internal global variables, and it seems to be more convenient. Has an object-oriented style. Readers are welcome to share their thoughts and whether it is good or not to write this way.

Next, let’s take a look at the complete code of the Winpop component:

(function(window, jQuery, undefined) {

    var HTMLS = {
        ovl: &#39;<p class="J_WinpopMask winpop-mask" id="J_WinpopMask"></p>&#39; + &#39;<p class="J_WinpopBox winpop-box" id="J_WinpopBox">&#39; + 
        &#39;<p class="J_WinpopMain winpop-main"></p>&#39; + &#39;<p class="J_WinpopBtns winpop-btns"></p>&#39; + &#39;</p>&#39;,
        alert: &#39;<input type="button" class="J_AltBtn pop-btn alert-button" value="确定">&#39;,
        confirm: &#39;<input type="button" class="J_CfmFalse pop-btn confirm-false" value="取消">&#39; + &#39;
        <input type="button" class="J_CfmTrue pop-btn confirm-true" value="确定">&#39;
    }

    function Winpop() {
        var config = {};
        this.get = function(n) {
            return config[n];
        }

        this.set = function(n, v) {
            config[n] = v;
        }
        this.init();
    }

    Winpop.prototype = {
        init: function() {
            this.createDom();
            this.bindEvent();
        },
        createDom: function() {
            var body = jQuery("body"),
                ovl = jQuery("#J_WinpopBox");

            if (ovl.length === 0) {
                body.append(HTMLS.ovl);
            }

            this.set("ovl", jQuery("#J_WinpopBox"));
            this.set("mask", jQuery("#J_WinpopMask"));
        },
        bindEvent: function() {
            var _this = this,
                ovl = _this.get("ovl"),
                mask = _this.get("mask");
            ovl.on("click", ".J_AltBtn", function(e) {
                _this.hide();
            });
            ovl.on("click", ".J_CfmTrue", function(e) {
                var cb = _this.get("confirmBack");
                _this.hide();
                cb && cb(true);
            });
            ovl.on("click", ".J_CfmFalse", function(e) {
                var cb = _this.get("confirmBack");
                _this.hide();
                cb && cb(false);
            });
            mask.on("click", function(e) {
                _this.hide();
            });
            jQuery(document).on("keyup", function(e) {
                var kc = e.keyCode,
                    cb = _this.get("confirmBack");;
                if (kc === 27) {
                    _this.hide();
                } else if (kc === 13) {
                    _this.hide();
                    if (_this.get("type") === "confirm") {
                        cb && cb(true);
                    }
                }
            });
        },
        alert: function(str, btnstr) {
            var str = typeof str === &#39;string&#39; ? str : str.toString(),
                ovl = this.get("ovl");
            this.set("type", "alert");
            ovl.find(".J_WinpopMain").html(str);
            if (typeof btnstr == "undefined") {
                ovl.find(".J_WinpopBtns").html(HTMLS.alert);
            } else {
                ovl.find(".J_WinpopBtns").html(btnstr);
            }
            this.show();
        },
        confirm: function(str, callback) {
            var str = typeof str === &#39;string&#39; ? str : str.toString(),
                ovl = this.get("ovl");
            this.set("type", "confirm");
            ovl.find(".J_WinpopMain").html(str);
            ovl.find(".J_WinpopBtns").html(HTMLS.confirm);
            this.set("confirmBack", (callback || function() {}));
            this.show();
        },
        show: function() {
            this.get("ovl").show();
            this.get("mask").show();
        },
        hide: function() {
            var ovl = this.get("ovl");
            ovl.find(".J_WinpopMain").html("");
            ovl.find(".J_WinpopBtns").html("");
            ovl.hide();
            this.get("mask").hide();
        },
        destory: function() {
            this.get("ovl").remove();
            this.get("mask").remove();
            delete window.alert;
            delete window.confirm;
        }
    };

    var obj = new Winpop();
    window.alert = function(str) {
        obj.alert.call(obj, str);
    };
    window.confirm = function(str, cb) {
        obj.confirm.call(obj, str, cb);
    };
})(window, jQuery);
Copy after login

The code is slightly more, the key points are as follows:

  • The author stole it I'm lazy and used jQuery. Please make sure you have introduced jQuery before using it

  • The custom component structure is eventually appended to the body, so before introducing the above js, please make sure The document has been loaded

  • The component has added the function of pressing ESC and clicking the mask layer to hide the component

  • Note: Although it is not used in this example destroy method, but readers can pay attention to delete window.alert and delete window.confirm in this method. The purpose of writing this is to ensure that after the custom component is destroyed, the Alert and Confirm controls are restored to the browser's built-in effects

  • If you add window.Winpop = Winpop at the end of the component, you can make the object global for other classes to call

Finally

As a front-end development engineer, I personally think that Javascript component development is a very interesting thing, and the fun can only be realized if you try it yourself. Front-end component development often requires the cooperation of Javascript, CSS and HTML to achieve twice the result with half the effort. The Winpop mentioned above is no exception. Here we provide you with a complete demo compressed package. Interested readers are welcome to spread the word.

The above is the content of developing a complete JavaScript component. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template