前端小白之每天學習記錄----js簡單的組件封裝

來源:互聯網
上載者:User

標籤:組件   query   play   參數   工廠   bad   新增內容   輸出   cdn   

設計模式:是解決問題的模板

關於設計模式,可以閱讀湯姆大叔的博文http://www.cnblogs.com/TomXu/archive/2011/12/15/2288411.html

這裡簡單介紹兩種設計模式:

1.單例模式:單例就是保證一個類只有一個執行個體

      eg:在JavaScript裡,實現單例的方式有很多種,其中最簡單的一個方式是使用對象字面量的方法,其字面量裡可以包含大量的屬性和方法:

var people = {    name: "lxb",    age: "22",    eat: function () {        console.log(‘eat‘);    }};

 

  

 

2.原廠模式:建造類型的模式, 重點是創造對象

      eg:可以建立許多有相同屬性,屬性的值不同的對象:

function CreateObj( name, age ){        var obj = new Object();        obj.name = name;        obj.age = age;        return obj;    }    var o1 = CreateObj( xx, xx );    var o2 = CreateObj( xx, xx );

組件:許多外掛程式組合在一起

想要封裝組件,首先要先搭建外掛程式

比如現在我們要搭建一個警告框外掛程式

警告框外掛程式: 1.整體架構準備第一步:定義一個警告框建構函式第二步:給這個建構函式加上方法    方法1:顯示警告框    方法2:隱藏警告框第三步:把建構函式執行個體化,並調用顯示方法顯示警告框
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <script>        //第一步:定義一個警告框建構函式        var popAlert = function (opt) {  //opt參數為外部可定製參數集合            this.opt = opt || {};   //未傳參時預設為空白        }
//第二步: //顯示警告框 popAlert.prototype.show = function () { var oDiv = document.createElement("div"); //建立一個div oDiv.setAttribute(‘class‘, ‘alert‘); //為div添加類名alert document.body.appendChild(oDiv); //把div輸出到body } //隱藏警告框 popAlert.prototype.hide = function () { }
     第三步: //測試:F12查看 window.onload = function () { var oAlertSuccess = new popAlert(); //執行個體化 oAlertSuccess.show();//顯示 } </script></head><body></body></html>

以上代碼會在body建立一個div

2.警告框外掛程式完成

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <!-- 從bootstrap複製的警告款樣式 -->     <!-- <link rel="stylesheet" href="./css/layout.css">  -->    <!-- 或者直接用bootstrap樣式 -->     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css">     <script>        //定義一個警告框建構函式        var popAlert = function (opt) {            this.opt = opt || {};        }        //顯示警告框        popAlert.prototype.show = function () {            //建立div            var oDiv = document.createElement("div"),                    that = this, //that 儲存建構函式構造的執行個體對象                    aClose;            //添加類名            this.opt[‘class‘]?// 判斷有無外部參數class            oDiv.classList.add( ‘alert‘, this.opt[‘class‘])                        :oDiv.classList.add( ‘alert‘,"alert-info");//外部沒有傳參數用預設的            //為div新增內容            oDiv.innerHTML = "<a href=‘javascript:;‘ class=‘close‘>x</a>"; //添加一個x的關閉標誌            oDiv.innerHTML += this.opt[‘content‘] || ‘請新增內容‘; //添加外部指定內容            //把div輸出到body下            document.body.appendChild(oDiv);              // 為所有x關閉標誌綁定點擊事件(重複遍曆,在後面會改正)            aClose = document.querySelectorAll(".alert > .close");            aClose.forEach(function( ele ){                ele.addEventListener( ‘click‘, function(){                      that.hide( this.parentNode );  //用建構函式的隱藏方法隱藏點擊的關閉標誌的父節點(即整個警告框)                });            });        }        //隱藏警告框        popAlert.prototype.hide = function ( obj ) {            obj.style.display = ‘none‘;        }         //測試:        window.onload = function () {               var oAlertkong = new popAlert();            oAlertkong.show();            var oAlertkong2 = new popAlert({                content: ‘這是預設樣式‘,                // class: ‘alert-success‘            });            oAlertkong2.show();            var oAlertSuccess = new popAlert({                content: ‘這是成功提示‘,                class: ‘alert-success‘            });            oAlertSuccess.show();            var oAlertWarning = new popAlert({                content: ‘這是警告提示‘,                class: ‘alert-warning‘            });            oAlertWarning.show();            var oAlertInfo = new popAlert({                content: ‘這是資訊提示‘,                class: ‘alert-info‘            });            oAlertInfo.show();            var oAlertDanger = new popAlert({                content: ‘這是危險提示‘,                class: ‘alert-danger‘            });            oAlertDanger.show();        }    </script></head><body></body></html>

3.把警告框外掛程式(popAlert)封裝在組件(module)裡面

分裝好的js部分(plugin.js):

; (function (window, undefined) {    var module = {}; //定義組件    //外掛程式1    var popAlert = function (opt) {        this.opt = opt || {};    }    // 輸出    popAlert.prototype.show = function () {        var oDiv = document.createElement("div"),            that = this,            aClose;        this.opt[‘class‘] ?            oDiv.classList.add(‘alert‘, this.opt[‘class‘])            : oDiv.classList.add(‘alert‘, "alert-info");        oDiv.innerHTML = "<a href=‘javascript:;‘ class=‘close‘>x</a>";        oDiv.innerHTML += this.opt[‘content‘] || ‘請新增內容‘;        document.body.appendChild(oDiv);    // 綁定事件        aClose = document.querySelectorAll(".alert > .close");        aClose.forEach(function (ele) {            ele.addEventListener(‘click‘, function () {                that.hide(this.parentNode);            });        });    }    popAlert.prototype.hide = function (obj) {        obj.style.display = ‘none‘;    };    module[‘popAlert‘] = popAlert; //為組件添加外掛程式一    window.module = module; //暴露組件到外部})(window, undefined); 

 測試輸出的html部分:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <!-- <link rel="stylesheet" href="./css/layout.css"> -->    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css">    <script src="./js/plugin.js"></script>    <script>        //封裝在plugin.js裡面        window.onload = function () {            var oAlertSuccess = new module.popAlert({                content: ‘這是成功提示‘,                class: ‘alert-success‘            });            oAlertSuccess.show();            var oAlertWarning = new module.popAlert({                content: ‘這是警告提示‘,                class: ‘alert-warning‘            });            oAlertWarning.show();            var oAlertInfo = new module.popAlert({                content: ‘這是資訊提示‘,                class: ‘alert-info‘            });            oAlertInfo.show();            var oAlertDanger = new module.popAlert({                content: ‘這是危險提示‘,                class: ‘alert-danger‘            });            oAlertDanger.show();        }    </script></head><body></body></html>

模態框外掛程式+警告框外掛程式:(建立plugin2.js)

; (function (window, undefined) {    var module = {};//定義組件    //外掛程式1:警告框    var popAlert = function (opt) {        this.opt = opt || {};    };    popAlert.prototype.show = function () {        var oDiv = document.createElement("div"),            that = this,            aClose;        this.opt[‘class‘] ?            oDiv.classList.add(‘alert‘, this.opt[‘class‘])            : oDiv.classList.add(‘alert‘, "alert-info");        oDiv.innerHTML = "<a href=‘javascript:;‘ class=‘close‘>x</a>";        oDiv.innerHTML += this.opt[‘content‘] || ‘請新增內容‘;        document.body.appendChild(oDiv);        var that = this;        aClose = document.querySelectorAll(".alert > .close");        aClose.forEach(function (ele) {            ele.addEventListener(‘click‘, function () {                that.hide(this.parentNode);            });        });    };    popAlert.prototype.hide = function (obj) {        obj.style.display = ‘none‘;    };    //外掛程式2:模態框    var popModal = function (opt) {        this.opt = opt || {};    };    //顯示    popModal.prototype.show = function () {        var that = this;        var modalHtml = "<div class=‘modal fade‘>";//進入的方式:飛入        modalHtml += "<div class=‘modal-dialog‘>";//布局        modalHtml += "<div class=‘modal-content‘>";//模態框盒子        //標題        modalHtml += "<div class=‘modal-header‘>";        modalHtml += "<button type=‘button‘ class=‘close‘>x</button>";        modalHtml += "<h4 class=‘modal-title‘>" + (this.opt[‘title‘] || ‘可定製title標題‘) + "</h4>"        modalHtml += "</div>";        //內容        modalHtml += "<div class=‘modal-body‘>";        modalHtml += this.opt[‘content‘] || ‘可定製content內容‘;        modalHtml += "</div>";        // 底部內容        modalHtml += "<div class=‘modal-footer‘>";        modalHtml += this.opt[‘footer‘] || ‘可定製footer底部內容‘;        modalHtml += "</div>";        //尾部標籤        modalHtml += "</div>";        modalHtml += "</div>";        modalHtml += "</div>";        //按鈕        modalHtml += "<h2>";        modalHtml += this.opt[‘tip‘] || "可定製tip提示資訊";        modalHtml += "</h2><button class=‘btn btn-primary btn-lg‘ data-toggle=‘modal‘ data-target=‘#myModal‘>";        modalHtml += this.opt[‘btn‘] || "可定製btn按鈕文本";        //輸出到bady        var oldHTML = document.body.innerHTML;    //儲存舊的文檔        document.body.innerHTML = oldHTML + modalHtml;//添加外掛程式        //綁定x點擊事件 關閉框        var that = this;        var oClose = document.querySelector(".modal .close")        oClose.addEventListener("click", function () {            that.hide(this);        });        //綁定顯示事件        var open = document.querySelector(".btn[data-toggle=modal]");        open.onclick = function () {            var oModal = document.querySelector(".modal");            oModal.style.display = ‘block‘;            oModal.classList.add(‘in‘);            //遮罩層            var backdrop = document.createElement("div"); //建立一個div            backdrop.setAttribute(‘class‘, ‘modal-backdrop in‘);    //為div添加類名            document.body.appendChild(backdrop);        }    }    popModal.prototype.hide = function (obj) {        var objParents = findNode(obj, "modal"); //當前.close的父輩元素 .modal        objParents.style.display = ‘none‘;//隱藏模態        document.body.removeChild(document.querySelector(".modal-backdrop"));        // document.querySelector(".modal-backdrop").style.display = "none";    }    //公用的方法:    //找到關閉按鈕的指定父節點    function findNode(obj, classname) {        var aClass;        var regExp = new RegExp(classname);        while (obj = obj.parentNode) {            aClass = Array.prototype.slice.call(obj.classList); //類數組--->數組            if (aClass.length && regExp.test(aClass[0]) && aClass[0].length == 5) {                break;            }        }        return obj;    }    //把外掛程式存入組件    module = {        popAlert: popAlert,        popModal: popModal    };    window.module = module;//把組件暴露到外部})(window, undefined);

 測試使用模態框:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css">    <script src="./js/plugin2.js"></script>    <script>        window.onload = function () {            var oModal = new module.popModal({                // title: ‘你好‘,                // content: ‘這是模態框的內容‘,                // footer:"你好啊",                // tip:"下面這個按鈕點一下",                // btn:"點我啊"            });            oModal.show();        }    </script></head><body></body></html>

  

前端小白之每天學習記錄----js簡單的組件封裝

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.