filter.js 2.99 KB
/**
 * 筛选JS
 * 暴露三个接口:注册回调、显示filter、隐藏filter
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/19
 */

var $ = require('jquery'),
    Hammer = require('hammer');

var $filter;

var fCbFn, hCbFn; //筛选和关闭的回调

var missStatus; //是否忽略选中状态

//隐藏筛选界面
function hideFilter() {
    $filter.addClass('hide');
}

//显示筛选界面
function showFilter() {
    $filter.removeClass('hide');
}

//主筛选项Tap事件句柄
function classifyTapEvt($this) {
    if ($this.hasClass('active')) {
        return;
    }

    $this.siblings('.active').removeClass('active');

    $this.addClass('active');
}

//子筛选项选中处理
function setSubClassify($this) {
    var $sub = $this.closest('.sub-classify');

    var $shower = $sub.siblings('.shower');

    var html, shower;

    if ($this.hasClass('chosed')) {
        return;
    }

    $sub.children('.chosed').removeClass('chosed');
    $this.addClass('chosed');

    html = $.trim($this.html());

    shower = $.trim($shower.html());

    $shower.html(
        shower.substring(0, shower.indexOf('</span>') + 7) + //拆分出shower的title
        html.substring(0, html.indexOf('<i')) //拆分选中筛选值
    );

    if ($this.index() === 0) {
        $shower.addClass('default');
    } else {
        $shower.removeClass('default');
    }

    return $sub;
}

//子筛选项Tap句柄
function subClassifyTapEvt($this) {
    var id = $this.data('id');

    var $sub;

    $sub = setSubClassify($this);

    if (fCbFn) {
        fCbFn({
            type: $sub.data('type'),
            id: id
        });
    }

    hideFilter();
}

//初始化筛选
function initFilter(opt) {
    var filterHammer;

    //注册回调
    fCbFn = opt.fCbFn;
    hCbFn = opt.hCbFn;

    missStatus = opt.missStatus;


    $filter = $('.filter-mask');

    filterHammer = new Hammer($filter[0]);
    filterHammer.on('tap', function(e) {
        var $this = $(e.target),
            $cur;

        if ($this.closest('.filter-body').length > 0) {
            $cur = $this.closest('.sub-item');
            if ($cur.length > 0) {

                //tap subclassify
                $cur = $this.closest('li');

                subClassifyTapEvt($cur);
            } else {

                //tap classify
                $cur = $this.closest('.classify-item');

                e.srcEvent.stopPropagation();

                classifyTapEvt($cur);
            }
        } else {
            hideFilter();

            if (hCbFn) {
                hCbFn();
            }
        }
    });
}

//重置筛选面板
function resetFilter() {
    if (typeof $filter === 'undefined') {
        return;
    }

    //重置子筛选项
    $('.sub-classify').each(function() {
        setSubClassify($(this).children(':first-child'));
    });

    //重置主筛选项
    classifyTapEvt($('.classify > :first-child'));
}

exports.initFilter = initFilter;

exports.showFilter = showFilter;

exports.hideFilter = hideFilter;

exports.resetFilter = resetFilter;