yii.captcha.js 2.06 KB
Newer Older
1 2 3
/**
 * Yii Captcha widget.
 *
Qiang Xue committed
4
 * This is the JavaScript widget used by the yii\captcha\Captcha widget.
5 6 7 8 9 10 11 12
 *
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
(function ($) {
Qiang Xue committed
13 14 15 16 17 18 19 20 21 22
    $.fn.yiiCaptcha = function (method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.yiiCaptcha');
            return false;
        }
    };
23

Qiang Xue committed
24 25 26 27
    var defaults = {
        refreshUrl: undefined,
        hashKey: undefined
    };
28

Qiang Xue committed
29 30 31 32 33 34 35 36
    var methods = {
        init: function (options) {
            return this.each(function () {
                var $e = $(this);
                var settings = $.extend({}, defaults, options || {});
                $e.data('yiiCaptcha', {
                    settings: settings
                });
37

Qiang Xue committed
38 39 40 41
                $e.on('click.yiiCaptcha', function () {
                    methods.refresh.apply($e);
                    return false;
                });
42

Qiang Xue committed
43 44
            });
        },
45

Qiang Xue committed
46 47 48 49 50 51 52 53 54 55 56 57 58
        refresh: function () {
            var $e = this,
                settings = this.data('yiiCaptcha').settings;
            $.ajax({
                url: $e.data('yiiCaptcha').settings.refreshUrl,
                dataType: 'json',
                cache: false,
                success: function (data) {
                    $e.attr('src', data.url);
                    $('body').data(settings.hashKey, [data.hash1, data.hash2]);
                }
            });
        },
59

Qiang Xue committed
60 61 62 63 64 65
        destroy: function () {
            return this.each(function () {
                $(window).unbind('.yiiCaptcha');
                $(this).removeData('yiiCaptcha');
            });
        },
66

Qiang Xue committed
67 68 69 70
        data: function () {
            return this.data('yiiCaptcha');
        }
    };
71 72
})(window.jQuery);