code.js 2.2 KB
/**
 * 注册/找回密码-验证码
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/8
 */
var $ = require('yoho.zepto');

module.exports = function(useInRegister) {
    var $captcha = $('#captcha'),
        $btnNext = $('#btn-next'),
        $captchaTip = $('#captcha-tip');

    var api = require('./api');
    var tip = require('../plugin/tip');

    var trim = $.trim;
    var showErrTip = tip.show;

    var urlMid = useInRegister ? 'register' : 'back';

    function countDown() {
        var count = 59,
            itime;

        itime = setInterval(function() {
            if (count === 0) {
                $captchaTip.text('重发验证码').removeClass('disable');
                clearInterval(itime);
            } else {
                $captchaTip.text('重发验证码 (' + count-- + '秒)');
            }
        }, 1000);
    }

    api.bindClearEvt();

    $captcha.bind('input', function() {
        if (trim($captcha.val()) !== '') {
            $btnNext.removeClass('disable');
        } else {
            $btnNext.addClass('disable');
        }
    });

    //重新发送验证码
    $captchaTip.on('touchstart', function() {
        if ($captchaTip.hasClass('disable')) {
            return;
        }

        $.ajax({
            type: 'POST',
            url: '/passport/' + urlMid + '/sendPhone'
        }).then(function (data) {
            if (data.code === 200) {
                $captchaTip.text('重发验证码 (60秒)').addClass('disable');
                countDown();
            } else {

                //验证码不正确,显示提示
                showErrTip(data.message);
            }
        });
    });

    $btnNext.on('touchstart', function() {
        if ($btnNext.hasClass('disable')) {
            return;
        }

        $.ajax({
            type: 'POST',
            url: '/passport/' + urlMid + '/verifycode',
            data: {
                verifyCode: trim($captcha.val())
            }
        }).then(function (data) {
            if (data.code === 200) {
                location.href = data.data;
            } else {

                //验证码不正确,显示提示
                showErrTip(data.message);
            }
        });
    });

    countDown();
};