city-swiper.js 2.25 KB
import Swiper from 'yoho-swiper';
import $ from 'yoho-jquery';
import Page from 'js/yoho-page';

class CitySwiper extends Page {
    constructor(data) {
        super();
        this.selector = {
            $swiperC: $('.city-swiper'),
            $swiper: $('.city-swiper .swiper-list').find('.swiper-container'),
            $slide: $('.city-swiper .swiper-list').find('.swiper-slide'),
            $swiperLine: $('.city-swiper .swiper-line'),
            $swiperList: $('.city-swiper .swiper-list')
        };
        this.provinceSwiper = '';
        this.citySwiper = '';
        this.init(data);
    }

    init(data) {
        let swiperParams = this.swiperParams(data);

        this.setStyle(data);
        this.provinceSwiper = new Swiper('.city-swiper #province-c', swiperParams);
        this.citySwiper = new Swiper('.city-swiper #city-c', swiperParams);
    }

    setStyle(data) {
        let lineHeight = this.selector.$swiperList.height() / data.lineNum;
        let lineTop = lineHeight / 2;

        if (data.hidePartingLine) {
            this.selector.$swiperLine.hide();
        }
        this.selector.$swiperLine.css('height', `${lineHeight}px`);
        this.selector.$swiperLine.css('margin-top', `-${lineTop}px`);
    }

    swiperParams(data) {
        let $thisSwiper = '';
        let newParams = {
            direction: 'vertical',
            slidesPerView: data.lineNum || 1,
            centeredSlides: data.centeredSlides,
            loop: data.true,
            observer: true,
            observeParents: true,
            slideToClickedSlide: true,
            onInit: (swiper) => {
                $thisSwiper = swiper.activeIndex;
                $thisSwiper = $(swiper.slides[`${$thisSwiper}`]);
                this.emit('citySwiperCb', $thisSwiper);
            },
            onSlideChangeEnd: (swiper) => {
                if ($(swiper.container[0]).index() === 0) {
                    this.citySwiper.slideTo(0, 1000, false); // 重选省份时,城市设置为第一个
                }
                $thisSwiper = swiper.activeIndex;
                $thisSwiper = $(swiper.slides[`${$thisSwiper}`]);
                this.emit('citySwiperCb', $thisSwiper);
            }
        };

        return newParams;
    }
}

module.exports = CitySwiper;