【重要】統一管理碎片程式碼,跟混亂程式碼說再見

阿9發表於2018-07-23

我們在日常運輸程式碼的時候,時常因為程式碼過於混亂而導致時間長了程式碼多了之後難以搬運,即便是老司機都得打起十二分精神,比如類似於下面這樣的程式碼(大家一眼劃過就行了):

$(document).ready(function(){
            if (!getCookie("showNotice")) {
                setCookie("showNotice", "1",1);
                document.querySelector(".shadowBg").style.display = "flex";
                document.querySelector(".new_year_notice span").addEventListener('click', function () {
                    document.querySelector(".shadowBg").style.display = "none";
                });
            }
             var newBanner = mcBanner();
            newBanner.switchBanner('mcBannerBox', '.mcBannerChild', '.bannerDotBox', 5000);
            
            sliderBox({
                id: document.getElementById('dynamic-list'),
                direction: 'top',
                intervalTime: 5000
            });
            sliderBox({
                id: document.getElementById('honor-box'),
                direction: 'left',
                intervalTime: 6000,
                clickLeft: document.getElementById('honor-box-left'),
                clickRight: document.getElementById('honor-box-right')
            });
            let _countTo = document.querySelectorAll('.countTo'),
                _countTo_len = _countTo.length;
            for (let i=0; i < _countTo_len; i++) {
                countTo({
                    id: _countTo[i],
                });
            }
            slideWord(document.getElementById('slideHonor'));
            $.ajax({
                url:'/payusercount',
                type:'GET',
                dataType:'json',
                success:function(data){
                    var _box = document.getElementById("box");
                    for (var i = 0; i < data.length; i++) {
                        _box.innerHTML += "<li><span>"+  data[i].mobile  +"</span><span>已購買"+  data[i].month  +"個月</span></li>"
                    }
                    sliderBox({
                        id: document.getElementById('box'),
                        direction: 'top',
                        intervalTime: 3000
                    });
                }
            })
            $.ajax({
                url:'/platform',
                type:'GET',
                dataType:'json',
                success:function(data){
                    document.getElementById("statistics1").dataset.count = data[0].number;
                    document.getElementById("statistics2").dataset.count = data[1].number;
                    document.getElementById("statistics3").dataset.count = data[2].number;
                    document.getElementById("statistics4").dataset.count = data[3].number;
                    let _countTo = document.querySelectorAll('.countTo'),
                    _countTo_len = _countTo.length;
                    for (let i=0; i < _countTo_len; i++) {
                        countTo({
                            id: _countTo[i],
                        });
                    }
                }
            })
        })
        $.ajax({
            url:'/news/category',
            type:'GET',
            dataType:'json',
            success:function(data){

                var artStr = '';
                var categoryCount = 0;
                for (var item in data.categories)
                {
                    if(categoryCount > 2) break;
                    categoryCount++;
                    var articleCount=0;
                    var temStr = ''
                    var strHead = '';
                    var strBottom = '';
                    var str = '';
                    strHead += '<li><div class="news-img"><img src="'+data.categories[item].path+'" alt=""/></div><div class="news-url">';
                    strBottom += '</div><p class="more"><a href="/news/category/'+(data.categories[item].id)+'">檢視更多>></a></p></li>'

                    newitem = data.categories[item].id;
                    for (var articleItem  in data.articleLists[newitem])
                    {
                        articleCount++;
                        if(articleCount == 5) break;
                        str += "<p><a href='/news/article/"+data.articleLists[newitem][articleItem].id+"'>";
                        str += data.articleLists[newitem][articleItem].name
                        str += "</a></p>";

                    };
                    temStr = strHead + str + strBottom;
                    artStr += temStr
                };
                $('.e-artical').append(artStr);
            }
        })
複製程式碼

這段程式碼好像還挺長的,其實僅僅是冰山一角。一個專案中如果都是這樣的程式碼,基本可以說是廢了,因為專案在日常不斷的迭代當中,我們就只能不斷地堆積程式碼,不斷地讓整個專案更加的混亂和臃腫。

另外不得不說的是,現在很多小夥伴都會用框架來開發專案,但是,請記住,只要你對自己有有足夠的信心足夠的隨意,你依然可以寫出很混亂的程式碼,相信我,真的!

下面獻上整理過後的程式碼,相關的解釋直接穿插到程式碼相應位置的註釋中,方便理解

$(document).ready(function(){
            var thisPageThings = (function () {
                 /*這外面可以寫可以在下面的物件的方法中
                  多次利用的函式,在這裡也可以認為是私有函式
                */
                return {
                     /*每次增加相關程式碼,請在物件裡面新建方法,
                  把新增的程式碼寫在新建的程式碼裡面,統一管理所有碎片程式碼,
                  把混亂的程式碼切割為一塊塊的碎片*/
                    addBan: function () {
                        $('.addBan').click(function () {
                            var id = $(this).data('id');
                            $.ajax({
                                url:'/addclick',
                                type:'GET',
                                data:{'id':id},
                                success:function(res){
                                    console.log(res);
                                }
                            })
                        });
                    },
                    onceModal: function () {
                        var res = document.cookie.indexOf("first_visit");
                        if(res == -1){
                            var exp =new Date();
                            console.log(exp.getTime());
                            exp.setTime(exp.getTime() + (21 - exp.getHours()) * 60 * 60 * 1000); //提前一小時吧
                            document.cookie ="first_visit=1;expires=" + exp.toGMTString(); //5秒測試
                            document.querySelector(".shadowBg").style.display = "flex";
                            document.querySelector(".new_year_notice span").addEventListener('click', function () {
                                document.querySelector(".shadowBg").style.display = "none";
                            });
                        }
                    },
                    mcBannerBox: function () {
                        $('.mcBannerChild').length > 1 && (function () {
                            var newBanner = mcBanner();
                            newBanner.switchBanner('mcBannerBox', '.mcBannerChild', '.bannerDotBox', 5000);
                        }());
                    },
                    dynamicList: function () {
                        $('#dynamic-list').children().length && sliderBox({
                            id: document.getElementById('dynamic-list'),
                            direction: 'top',
                            intervalTime: 5000
                        });
                    },
                    honorBox: function () {
                        $('#honor-box').children().length && sliderBox({
                            id: document.getElementById('honor-box'),
                            direction: 'left',
                            intervalTime: 6000,
                            clickLeft: document.getElementById('honor-box-left'),
                            clickRight: document.getElementById('honor-box-right')
                        });
                    },
                    slideHonor: function () {
                        slideWord(document.getElementById('slideHonor'));
                    },
                    payusercountAjax: function () {
                        var _this = this;
                        $.ajax({
                            url:'/payusercount',
                            type:'GET',
                            dataType:'json',
                            success:function(data){
                                _this.event.publish('payusercountAjax', data);

                            }
                        });
                    },
                    platformAjax: function () {
                        var _this = this;
                        $.ajax({
                            url:'/platform',
                            type:'GET',
                            dataType:'json',
                            success:function(data){
                                _this.event.publish('platformAjax', data);
                            }
                        })
                    },
                    categoryAjax: function () {
                        var _this = this;
                        $.ajax({
                            url:'/news/category',
                            type:'GET',
                            dataType:'json',
                            success:function(data){
                                _this.event.publish('categoryAjax', data);
                            }
                        })
                    },
                    //此處放置所有的訂閱
                    allSubscription: function () {
                        this.event.subscribe('payusercountAjax', function (data) {
                            var _box = document.getElementById("box");
                            for (var i = 0; i < data.length; i++) {
                                _box.innerHTML += "<li><span>"+  data[i].mobile  +"</span><span>已購買"+  data[i].month  +"個月</span></li>"
                            }
                            sliderBox({
                                id: document.getElementById('box'),
                                direction: 'top',
                                intervalTime: 3000
                            });
                        });
                        this.event.subscribe('platformAjax', function (data) {
                            var _countTo = document.querySelectorAll('.countTo'),
                                _countTo_len = _countTo.length;
                            for (var i=0; i < _countTo_len; i++) {
                                document.getElementById("statistics" + i).dataset.count = data[i].number;
                                countTo({
                                    id: _countTo[i]
                                });
                            }
                        });
                        this.event.subscribe('categoryAjax', function (data) {
                            var artStr = '';
                            var categoryCount = 0;
                            for (var item in data.categories)
                            {
                                if(categoryCount > 2) break;
                                categoryCount++;
                                var articleCount=0;
                                var temStr = '';
                                var strHead = '';
                                var strBottom = '';
                                var str = '';
                                strHead += '<li><div class="news-img"><img src="'+data.categories[item].path+'" alt=""/></div><div class="news-url">';
                                strBottom += '</div><p class="more"><a href="/news/category/'+(data.categories[item].id)+'">檢視更多>></a></p></li>';

                                newitem = data.categories[item].id;
                                for (var articleItem  in data.articleLists[newitem])
                                {
                                    articleCount++;
                                    if(articleCount == 5) break;
                                    str += "<p><a href='/news/article/"+data.articleLists[newitem][articleItem].id+"'>";
                                    str += data.articleLists[newitem][articleItem].name;
                                    str += "</a></p>";

                                }
                                temStr = strHead + str + strBottom;
                                artStr += temStr
                            }
                            $('.e-artical').append(artStr);
                        });
                    }
                };
            }());
            //此處為上面自執行程式碼的相關配置,如果需要組織程式碼比如說一些設計模式
            (function () {
                //釋出和訂閱的方法模板,這裡其實就是一個釋出訂閱模式
                var event = {
                    clientList: [],
                    subscribe: function (key, fn) {
                        if (!this.clientList[key]) {
                            this.clientList[key] =[];
                        }
                        this.clientList[key].push(fn);
                    },
                    publish: function () {
                        var key = Array.prototype.shift.call( arguments ),
                            fns = this.clientList[ key ];

                        if ( !fns || fns.length === 0 ) {
                            return false;
                        }
                        for ( var i = 0, fn; fn = fns[ i++ ]; ) {
                            fn.apply( this, arguments);
                        }
                    }
                };
                //將釋出訂閱的方法整合到要使用的物件中
                var installEvent = function (obj) {
                        obj[ 'event' ] = event;
                };
                
                installEvent( thisPageThings );
                //統一執行所有的程式碼碎片
                for (var thing in thisPageThings) {
                    typeof thisPageThings[thing] === 'function' && thisPageThings[thing]();
                }
            }());
        });
複製程式碼

從一開始就讓程式碼結構化是很有好處的,一方面提高可讀性,另一方面為以後的擴充套件提供了想象空間,比如自執行的相關配置可以整理出一個公用檔案,方便隨處可用;就算只有單個地方會用到,這麼個結構就很方便我們做到DRY——don't repeat yourself!


相關文章