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

var $ = require('yoho.zepto');

var $filter = $('.filter-mask, .filter-body');

var $classify = $filter.find('.classify'),
    $subClassify = $filter.find('.sub-classify');

var cbFn;

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

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

//注册sub-classify点击后的回调
function registerCbFn(cb) {
    cbFn = cb;
}

//设置完高度后显示sub并设置选中
$classify.children(':first-child').addClass('active'); //T:不在HTML中使用{{#if @first}}active{{/if}}来初始化active为避免sub设置高度时的闪烁

//classify switch
$classify.delegate('.classify-item', 'tap', function() {
    var $this = $(this);

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

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

    $this.addClass('active');
});

//点击Mask隐藏筛选界面
$filter.filter('.filter-mask').tap(function() {
    hideFilter();
});

$subClassify.delegate('li', 'tap', function(e) {
    var $this = $(this),
        id = $this.data('id');

    var $sub = $this.closest('.sub-classify');

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

    var html, shower;

    e.stopPropagation();

    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');
    }

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

    hideFilter();
});


exports.showFilter = showFilter;

exports.hideFilter = hideFilter;

exports.registerCbFn = registerCbFn;