单例模式的滚屏加载示例代码

阅读更多

基于jquery,该代码已经在http://hub.olympic.org/中使用,各位有需要的可以参考实现逻辑:

 

(function(UFA){
    var $ = jQuery;
    var PageLoader = function(){
        this.init();
    };
    PageLoader.prototype.reset = function(options){
        var settings = $.extend({
            container: '#',
            getParams: function(){
                return {};
            },
            getUrl: function(){
                return '#';
            },
            offset : 0,
            pageSize : 10
        }, options);

        settings.isLoading = false;
        settings.isEnd = false;

        this.settings = settings;
        this.$container = $(this.settings.container);
    };
    PageLoader.prototype.init = function(){
        var self = this;
        $(window).on('scroll', function(){
            var $container = self.$container;
            if(!self.$container || self.$container.length < 1 || self.settings.isLoading || self.settings.isEnd){
                return;
            }
            var listPos = $container.offset().top + $container.height();
            if(listPos <= 0){
                return;
            }
            var docPos = (window.innerHeight ? window.innerHeight : $(window).height()) + $(window).scrollTop();;
            if (docPos + 10 >= listPos) {
                var offset = self.settings.offset + self.settings.pageSize;
                self.doSearch(offset);
            }
        });
    };

    PageLoader.prototype.doSearch = function(offset){
        var self = this;
        offset = (offset && offset) > 0 ? offset : 0;
        this.settings.offset = offset;
        this.settings.isLoading = true;

        var style = 'normal';
        if(offset == 0){
            this.settings.isEnd = false;
        }else{
            style = 'scroll';
        }

        var params = this.settings.getParams();
        params['offset'] = offset;
        var url = this.settings.getUrl();

        UFA.ajax({
            type:'post',
            url: url,
            data: params,
            dataType : 'html',
            style: style,
            success:function(html){
                var html = $.trim(html);
                if(html == '' || html.indexOf('

') != -1){ self.settings.isEnd = true; if(offset != 0){ html = ''; } } if(offset == 0){ self.$container.html(html); }else{ self.$container.append(html); } }, error:function(){ UFA.Dialog.alert("Loading page failed, please try again"); }, complete:function(){ self.settings.isLoading = false; UFA.removeScrollLoading(); } }) }; window['_globalPageLoader_'] = new PageLoader() UFA.PageLoader = function(options){ window['_globalPageLoader_'].reset(options); }; UFA.PageLoader.prototype.doSearch = function(offset){ window['_globalPageLoader_'].doSearch(offset); }; })(UFA);

 

你可能感兴趣的:(单例模式的滚屏加载示例代码)