"Original" Development of a complete JavaScript component

Source: Internet
Author: User

As a developer, you should all know that there are some built-in controls in the browser: alert,confirm, etc., but these controls are often different depending on the browser's producers, and the visual effects often do not meet the requirements of the UI designer. More importantly, the style of such built-in controls is difficult to unify with the design style of various different styles of Internet products. As a result, excellent front-end developers each develop their own personalization controls to replace the controls built into the browser. Of course, this kind of components on the network has been countless very good, writing this article is not to show how good I developed this component, nor to show off what, just hope that in this way, with more developers to communicate with each other, learn from each other and progress together. Well, don't say much nonsense, so to speak.

function Introduction
    • Replace the alert, confirm control that comes with your browser
    • Custom interface Styles
    • Used in a way that is basically consistent with built-in controls
Effect Preview

1. Alert control

2. Confirm Control

3, complete code, online preview (see bottom, provide compression package download)

Development process1. Component Structure Design

First, let's look at the basic use of built-in components:

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

To ensure that our component usage is consistent with the built-in controls, we must consider overwriting the built-in controls. In view of the unified style of component development, ease of use, easy maintenance, and object-oriented features, I plan to use the custom alert and confirm methods as an instance method of a class (winpop), and finally to overwrite the system's built-in controls with an instance method. In order to achieve this 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);};

It is important to note that because the browser's built-in controls can block the browser's other behavior, and our custom components do not have this capability, in order to be as uniform as possible, as seen on the preview, we use a full-screen translucent mask layer when we play out the custom component. It is precisely for these reasons that the use of the confirm component has also made some minor adjustments, from the built-in return Boolean to the way the callback function is used, to ensure that the "OK" and "Cancel" logic can be added correctly. As a result, the way a custom component is used becomes the following form:

alert("自定义Alert组件");confirm("关闭自定义Confirm组件?", function(flag){    if (flag) {        alert("True");    } else {        alert("False");    }});
2. Component Code Design

Before we formally introduce the code for the Winpop component, let's 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);

It is a more recommended practice to wrap our component code with a self-executing anonymous function to minimize global pollution and finally to attach our class to the global Window object.

The GET, set method in the constructor is not necessary, but the author's personal habits, I think this write can be configured parameters and other components of the internal global variables cache and read the call way, it seems to be more object-oriented type. Readers are welcome to talk about their own ideas, to say whether this is good or not.

Next we'll look at the complete code for the Winpop component:

(Function (window, jQuery, undefined) {var htmls = {ovl: ' <div class= "J_winpopmask winpop-mask" id= "J_winpop Mask "></div> ' + ' <div class=" J_winpopbox winpop-box "id=" J_winpopbox "> ' + ' <div class=" J_winpopmain  Winpop-main "></div> ' + ' <div class=" J_winpopbtns winpop-btns "></div> ' + ' </div> ', alert: ' <input type= ' button ' class= ' j_altbtn pop-btn alert-button ' value= ' OK ' > ', confirm: ' <input type= ' button ' class= "J_cfmfalse pop-btn confirm-false" value= "Cancel" > ' + ' <input type= "button" class= "J_cfmtrue pop-btn        Confirm-true "value=" OK "> '} 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 = = =) {_this.hide ();                    } else if (kc = = =) {_this.hide ();                    if (_this.get ("type") = = = = "Confirm") {CB && CB (TRUE);        }                }            });                }, Alert:function (str, btnstr) {var str = typeof str = = = ' String '? 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 = = = ' String '? 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);

The code is slightly more, the key to do the following points:

    • I stole the lazy, using jquery, before using to ensure that you have introduced the jquery
    • The custom component structure is eventually appended to the body, so before you introduce JS, make sure the document is loaded and finished
    • Component adds the ability to hide components by pressing ESC, point mask Layer
    • Note: Although the method is not used in this example destory , reader friends can note the and in this method to ensure that the delete window.alert delete window.confirm alert, confirm control is restored to the browser's built-in effect after the custom component is destroyed
    • Component Finally, if you add it window.Winpop = Winpop , you can globally make the object available for other classes to call.
At last

As a front-end development engineer, personally feel that the development of JavaScript components is a very interesting thing, in which the fun can only be realized if you try it yourself. Front-end component development often requires JavaScript, CSS and HTML to cooperate with each other, in order to do less, the above mentioned winpop is no exception, here to provide you with a complete demo compression package, interested readers friends, welcome to spread.

Author blog: Hundred Yards villa

"Original" Development of a complete JavaScript component

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.