goods-list.js 2.12 KB
/*
 * @Author: Targaryen
 * @Date: 2017-04-21 13:36:34
 * @Last Modified by: Targaryen
 */

const $ = require('yoho-jquery');
const lazyLoad = require('yoho-jquery-lazyload');
const yoho = require('js/yoho-app');
const qs = require('yoho-qs');
const cookie = require('yoho-cookie');

/**
 * 获取 APP 传过来的参数
 */
const getChannel = {
    1: 'boys',
    2: 'girls',
    3: 'kids',
    4: 'lifestyle',
    '1,2,3,4': 'all'
};

let $goodsContainer = $('#goodsContainer');
let $container = $('#container');
let channel = getChannel[qs.yh_channel] || cookie.get('_Channel');
let page = 1;
let beforeScroll = document.body.scrollTop; // 滚动前位置记录
let onSearching = false; // 是否正在搜索

const loadGoodsList = () => {

    if (onSearching) {
        return false;
    }

    onSearching = true;
    $.ajax({
        method: 'get',
        url: location.protocol + '//m.yohobuy.com/product/sale/search?type=discount&order=1',
        data: {
            yh_channel: channel,
            page: page++,
            isApp: yoho.isApp,
            from: 'seckill'
        },
        complete: function() {
            onSearching = false;
        },
        success: function(result) {
            let $result = $(result);

            let noResult = !result || result.length < 1 || (result.list && result.list.length < 1);

            if (noResult) {
                return false;
            }

            $container.append($result);
            $goodsContainer.removeClass('hide');
            lazyLoad($result.find('img'));
        }
    });
};

/**
 * 当scroll到1/2$goodsContainer高度后继续请求下一页数据
 */
const scrollHandler = function() {
    if ($(window).scrollTop() > $goodsContainer.height() * 0.6) {
        loadGoodsList();
    }
};

/**
 * 滚动加载
 */
$(window).scroll(function() {
    setTimeout(function() {
        let afterScroll = document.body.scrollTop;

        if (afterScroll - beforeScroll > 0) {
            window.requestAnimationFrame(scrollHandler);
            beforeScroll = afterScroll;
        } else {
            return false;
        }
    }, 5);
});

$(function() {
    loadGoodsList();
});