template.js 9.73 KB
/**
 * 模板页js
 * @author: xuqi(qi.xu@yoho.cn)
 * @date;2015/4/14
 */

var $ = require('jquery'),
    _ = require('underscore'),
    Mustache = require('mustache'),
    timer = null;

require('lazyload');

/**
 * 页面加载初始化
 */
exports.init = function() {
    $(function() {
        var $navItem = $('#goods-nav .nav-item'),
            $goodsContainer = $('#goods-content'),
            $goodList = $('#goods-content > div'),
            $npc = $goodList.filter('.new-patterns-container'),
            $svc = $goodList.filter('.sales-volume-container'),
            $pc = $goodList.filter('.price-container'),
            tpl; //商品信息模板

        //筛选相关变量
        var curFilter = {
                brand: 0,
                msort: 0,
                color: 0,
                size: 0,
                price: 0,
                discount: 0
            },
            navInfo = {
                newest: {
                    direction: 1, //排序方向;NOTE:最新保持升序排序
                    reload: false, //是否需要重新加载
                    deviation: $npc.children('.good-info').length,
                    end: false
                },
                sale: {
                    direction: 1,
                    reload: true,
                    deviation: 0,
                    end: false
                },
                price: {
                    direction: 1,
                    reload: true,
                    deviation: 0,
                    end: false
                }
            },
            classifyItemTpl = '<li data-type="{{type}}" data-id="{{id}}"><span class="text">{{name}}</span></li>',
            $screen = $('#screen-content, #screen-mask'),
            $prevFocusNav = $navItem.filter('.focus'), //初始化为已选项
            classification; //分类数据

        //read good-info template
        $.get('/tpl/readTpl', function(data) {
            if (data.success) {
                tpl = data.data;
                Mustache.parse(tpl);
            }
        });

        Mustache.parse(classifyItemTpl); //cache tpl

        /**
         * Mustache 渲染数组数据
         * @params data Array 数据数组
         * @return html html字符串
         */
        function renderArrData(data) {
            var i = 0,
                html = '';
            for (i = 0; i < data.length; i++) {
                html += Mustache.render(classifyItemTpl, data[i]);
            }
            return html;
        }

        /**
         * 获取当前选中导航的类别
         * @return string/undefined
         */
        function getFocusNavType() {
            var type;
            if ($prevFocusNav.hasClass('sales-volume-nav')) {
                type = 'sale';
            } else if ($prevFocusNav.hasClass('price-nav')) {
                type = 'price';
            } else if ($prevFocusNav.hasClass('new-patterns-nav')) {
                type = 'newest';
            }
            return type;
        }

        /**
         * 查找当前状态下的商品列表并填充HTML
         */
        function search() {
            var type = getFocusNavType(),
                setting = {},
                nav;

            nav = navInfo[type];

            //请求数据setting
            $.extend(setting, curFilter, {
                type: type,
                direction: nav.direction,
                deviation: nav.deviation
            });

            if (nav.reload) {
                setting.deviation = 0;
            } else if (nav.end) {
                //不需要重新加载并且数据请求结束
                return;
            }

            $.ajax({
                type: 'GET',
                url: '/tpl/search',
                data: setting
            }).then(function(data) {
                var html = '',
                    $container,
                    res,
                    goods,
                    len,
                    i;
                if (data.success) {
                    res = data.data;
                    goods = res.goods;
                    len = goods.length;

                    //插入HTML
                    switch (setting.type) {
                        case 'newest':
                            $container = $npc;
                            break;
                        case 'price':
                            $container = $pc;
                            break;
                        case 'sale':
                            $container = $svc;
                            break;
                    }
                    for (i = 0; i < len; i++) {
                        html += Mustache.render(tpl, goods[i]);
                    }
                    if (nav.reload) {
                        $container.html(html);
                    } else {
                        $container.append(html);
                    }

                    //lazyload
                    $('img.lazy').lazyload({
                        container: $container
                    });
                    //手动加载前4个
                    $container.find('img.lazy:lt(4)').lazyload({
                        event: 'load'
                    });
                    //重置navInfo
                    if (res.end) {
                        nav.end = true;
                    }
                    nav.reload = false;
                    nav.deviation = setting.deviation + len;
                }
            });
        }
        //读取筛选时的分类信息
        $.get('/tpl/classification', function(data) {
            var c,
                html;
            if (data.success) {
                classification = data.data;
                for (c in classification) {
                    if(classification.hasOwnProperty(c)) {
                        $('#sub-' + c).html(renderArrData(classification[c]));
                    }
                }
            }
        });

        //img lazyload
        $('img.lazy').lazyload({
            skip_invisible : false
        });

        /**
         * 导航 touch/click处理句柄
         */
        function navTouchEvt(e) {
            var $cur = $(e.currentTarget),
                type;

            if ($cur.hasClass('screen-nav')) {
                //筛选
                $screen.toggleClass('hide');
                $prevFocusNav.toggleClass('focus');
                $cur.toggleClass('focus');
            } else {
                if ($cur.hasClass('focus')) {
                    return;
                }

                $prevFocusNav = $cur;

                $navItem.removeClass('focus');
                $cur.addClass('focus');

                type = getFocusNavType(); //当前focus项(new/sale/price)

                $goodList.addClass('hide');
                switch (type) {
                    case 'newest':
                        $npc.removeClass('hide');
                        break;
                    case 'sale':
                        $svc.removeClass('hide');
                        break;
                    case 'price':
                        $pc.removeClass('hide');
                        break;
                }

                if (navInfo[type].reload) {
                    search();
                }
            }
        }

        //切换“最新”,“销量”,“价格”以及“筛选”功能
        $('#goods-nav').delegate('.nav-item', 'touchstart', function(e) {
            e.preventDefault();
            navTouchEvt(e);
        }).delegate('.nav-item', 'click', function(e) {
            navTouchEvt(e);
        });

        /**
         * 筛选分类点击事件句柄
         */
        function scTouchEvt(e) {
            var $cur = $(e.currentTarget),
                cs = ['brand', 'msort', 'color', 'size', 'price', 'discount'],
                curType;

            if ($cur.hasClass('active')) {
                return;
            }

            $('#screen-content .c-item').removeClass('active');
            $cur.addClass('active');

            curType = _.filter(cs, function(c) {
                return $cur.hasClass(c);
            });

            $('.sub-classify:not(.hide)').addClass('hide');
            $('#sub-' + curType).removeClass('hide');
        }

        $('#screen-content').delegate('.c-item', 'touchstart', function(e) {
            e.preventDefault();
            scTouchEvt(e);
        }).delegate('.c-item', 'click', function(e) {
            scTouchEvt(e);
        });

        /**
         * 筛选
         * @params string 数据id
         * @params string 数据类型
         * @name string 值
         * @navNam string 最新/销量/价格
         * @direction int 0(降序)/1(升序)
         */
        function doFilter(id, type, name, navName) {
            var $shower = $('#show-' + type),
                att,
                req;
            //更新当前过滤项
            curFilter[type] = id;

            //更新显示值
            if (id === 0) {
                $shower.addClass('default');
            } else {
                $shower.removeClass('default');
            }

            $shower.text(name);

            //重置reload
            for (att in navInfo) {
                if (navInfo.hasOwnProperty(att)) {
                    navInfo[att].reload = true;
                }
            }
            search();
        }

        /**
         * 筛选子类点击事件句柄
         */
        function subScTouchEvt(e) {
            var cur = e.currentTarget,
                $cur = $(cur),
                $parent = $cur.closest('ul'),
                id = cur.dataset.id * 1,
                type = $parent[0].dataset.type,
                name = $cur.children('.text').text();

            doFilter(id, type, name);
        }

        $('.sub-classify').delegate('li', 'click', function(e) {
            subScTouchEvt(e);
        });
    });
};