search

Home  >  Q&A  >  body text

代码重构 - Javascript Infinite Scroll,如何重构这一段代码

用途

当用户手机 scroll 的时候,自动加载分页中的内容。如何让下面这一段代码更优美

代码

javascript//网址:http://xxx.com/game/top-hot/p/1/
//需要先引入 jquery.min.js 库
    var pageAutoLoad = [];
    pageAutoLoad.page = 1 || 1;
    pageAutoLoad.pageTotal = 2 || 1;
    pageAutoLoad.nextUrl = "\/game\/top-hot\/p\/PAGE\/" || '';
    pageAutoLoad.selector = {
        content: '.list_game ul',
        page: '.page_load'
    }
javascript//全局公用部分
//文件位置 /public/js/init.js
$(function(){
    if (typeof pageAutoLoad != 'undefined') {
        $(window).scroll(function () {
            loadData();
        });
    }
});

var totalheight = 0;
function loadData() {
    totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
    if ($(document).height() <= totalheight) {

        if (pageAutoLoad.page > pageAutoLoad.pageTotal) {
            return;
        }

        var nextPage = pageAutoLoad.page + 1;
        var nextUrl = pageAutoLoad.nextUrl.replace('PAGE', nextPage);

        $.ajax({
            url: nextUrl,
            type: 'GET',
            dataType: 'html',
            error: function () {
                $('.more-link').trigger('click');
            },
            success: function (html) {
                var htmlContent = $(html).find(pageAutoLoad.selector.content).html();
                var htmlPage = $(html).find(pageAutoLoad.selector.page).html();

                $(pageAutoLoad.selector.content).append(htmlContent);
                $(pageAutoLoad.selector.page).html(htmlPage);

                pageAutoLoad.page = nextPage;
            }
        });
    }
}

迷茫迷茫2819 days ago781

reply all(3)I'll reply

  • 阿神

    阿神2017-04-10 14:55:58

    建议你还是用一个类来实现这个组件,参数设计的话可以参考以下

    1. current_page //当前页
    2. total_page //总页
    3. fetch_url //加载地址(http://xxx.com/game/top-hot/p)
    4. url_generate_method //组件真实加载地址的生成函数(传入fetch_url和current_page)
    5. success_callback //加载成功后的回调
    6. error_callback //失败的回调
      ...

    不喜欢回调的方式可以基于jquery的自定义事件来解决。
    写法大致就是$.fn.customName = function (options) {...}
    然后调用的时候:$('selector').customName(options)


    javascript// 组件定义
    $.fn.pageAutoLoad = function (options) {
        var $element = $(this);
        var default_options = {
            current_page: 1,
            total_page: 2,
            fetch_url: undefined,
            url_generate_method: function (url, page) {
                return url + '/' + page;
            },
            success_callback: function (response, status) {},
            error_callback: function (error_msg) {}
        };
    
        options = $.extend({}, default_options, options);
    
        var loaddata = function () {
            $.ajax({
                url: options.url_generate_method(options.fetch_url, options.current_page),
                type: 'GET',
                dataType: 'html',
                error: function (jqxhr, status, error) {
                    options.error_callback(error, status, jqxhr);
                },
                success: function (jqxhr, status, response) {
                    // 更改当前的页数
                    options.current_page += 1;
                    options.success_callback(response, status, jqxhr);
                };
            });
        };
    
        $element.on('load_page', loaddata);
    }
    
    // 外部调用
    $(window).scroll(function () {
        var options = {
            fetch_url: "http://xxx.com/game/top-hot/p",
            url_generate_method: function (url, page) {
                return url + '/' + page + '/';
            },
            success_callback: function (html) {
                //你的success
            }
        };
        $('.more-link').pageAutoLoad(options);
    
        //先判断是否满足加载条件,这里就不写了,以下是满足条件后的代码
        $('.more-link').trigger('load_page');
    }
    

    reply
    0
  • 黄舟

    黄舟2017-04-10 14:55:58

    帮你把格式调了下:

    //网址:http://xxx.com/game/top-hot/p/1/
    //需要先引入jquery.min.js库
    var pageAutoLoad = {
        page: 1,
        pageTotal: 2,
        nextUrl: "\/game\/top-hot\/p\/PAGE\/",
        selector: {
            content: '.list_game ul',
            page: '.page_load'
        }
    };
    
    //全局公用部分
    //文件位置 /public/js/init.js
    $(function(){
        var totalheight = 0;
        function loadData() {
            totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
            if ($(document).height() <= totalheight) {
                if (pageAutoLoad.page > pageAutoLoad.pageTotal) {
                    return;
                }
                var nextPage = pageAutoLoad.page + 1;
                var nextUrl = pageAutoLoad.nextUrl.replace('PAGE', nextPage);
                $.ajax({
                    url: nextUrl,
                    type: 'GET',
                    dataType: 'html',
                    error: function () {
                        $('.more-link').trigger('click');
                    },
                    success: function (html) {
                        var htmlContent = $(html).find(pageAutoLoad.selector.content).html();
                        var htmlPage = $(html).find(pageAutoLoad.selector.page).html();
                        $(pageAutoLoad.selector.content).append(htmlContent);
                        $(pageAutoLoad.selector.page).html(htmlPage);
                        pageAutoLoad.page = nextPage;
                    }
                });
            }
        }
        if (typeof pageAutoLoad !== 'undefined') {
            $(window).scroll(function () {
                loadData();
            });
        }
    });
    

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 14:55:58

    重構如下:

    主要是提取邏輯並抽象。

    $.extend({
        InfiniteScroll: function(options) {
            var $window = $(window), $document = $(document);
    
            options = $.extend({
                onsuccess: function() {},
                onerror: function() {},
                onexhaust: function() {}
            }, options);
    
            function onscroll() {
                if ($document.height() <= $window.height() + $window.scrollTop() + 10)
                    if (options.pageNum + 1 <= options.pageCount)
                        load();
                    else
                        options.onexhaust(data);
            }
            function load() {
                var url = options.getUrl(options.pageNum + 1);
    
                $.ajax({
                    url: url,
                    type: 'GET',
                    dataType: 'html',
                    error: error,
                    success: success
                });
            }
            function success(data) {
                options.onsuccess(data);
            }
            function error() {
                options.onerror();
            }
    
            return {
                onscroll: onscroll
            }
        }
    });
    
    $(function(){
        $(window).scroll($.InfiniteScroll({
            pageNum: 1,
            pageCount: 2,
            urlTemplate: '/game/top-hot/p/%PAGE%/',
            selector: {
                content: '.list_game ul',
                page: '.page_load'
            }, 
            getUrl: function(pageNum) {
                var url = this.urlTemplate.replace(/%PAGE%/g, pageNum);
    
                return url;
            },
            onsuccess: function(data) {
                var selector = this.selector,
                    $data = $(data),
                    content = $data.find(selector.content).html(),
                    page = $data.find(selector.page).html();
    
                $(selector.content).append(content);
                $(selector.page).html(page);
    
                this.pageNum++;
            },
            onerror: function() {
                $('.more-link').trigger('click');
            }
        }).onscroll);
    });
    

    reply
    0
  • Cancelreply