Jquery插件写法

(function ($) {


    $.fn.scrollPagination = function (options) {

        var opts = $.extend($.fn.scrollPagination.defaults, options);
        var target = opts.scrollTarget;
        if (target == null) {
            target = obj;
        }
        opts.scrollTarget = target;

        return this.each(function () {
            $.fn.scrollPagination.init($(this), opts);
        });

    };

    $.fn.stopScrollPagination = function () {
        return this.each(function () {
            $(this).attr('scrollPagination', 'disabled');
        });

    };

    $.fn.scrollPagination.loadContent = function (obj, opts) {
        var target = opts.scrollTarget;
        var mayLoadContent = $(target).scrollTop() + opts.heightOffset >= $(document).height() - $(target).height();

        if (mayLoadContent&& opts.lock) {
            if (opts.beforeLoad != null) {
                opts.beforeLoad();
            }
            // alert(1);
            //加载数据的时候把lock设为false
            opts.lock = false;
            $(obj).children().attr('rel', 'loaded');
            // alert(2);
            $.ajax({
                type: 'GET',
                url: opts.contentPage,
                data: opts.contentData,
                async: false,
                success: function (data) {
                    //$(obj).append(data);
                    //alert(data);
                    //加载成功后把lock设为true,可以进行下一次request
                    opts.lock = true;
                    var objectsRendered = $(obj).children('[rel!=loaded]');

                    if (opts.afterLoad != null) {
                        opts.afterLoad(objectsRendered, data, opts);
                    }
                },
                dataType: 'json'
            });
        }

    };

    $.fn.scrollPagination.init = function (obj, opts) {
        var target = opts.scrollTarget;
        $(obj).attr('scrollPagination', 'enabled');

        $(target).scroll(function (event) {
            if ($(obj).attr('scrollPagination') == 'enabled') {
                $.fn.scrollPagination.loadContent(obj, opts);
            }
            else {
                event.stopPropagation();
            }
        });

        $.fn.scrollPagination.loadContent(obj, opts);

    };

    $.fn.scrollPagination.defaults = {
        'contentPage': null,
        'contentData': {},
        'beforeLoad': null,
        'afterLoad': null,
        'scrollTarget': null,
        'heightOffset': 0,
        'lock': true
    };
})(jQuery);

 

posted @ 2016-04-28 09:23  幻想家~  阅读(168)  评论(0编辑  收藏  举报