yii.js 12.6 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9
/**
 * Yii JavaScript module.
 *
 * @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
 */
Qiang Xue committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34

/**
 * yii is the root module for all Yii JavaScript modules.
 * It implements a mechanism of organizing JavaScript code in modules through the function "yii.initModule()".
 *
 * Each module should be named as "x.y.z", where "x" stands for the root module (for the Yii core code, this is "yii").
 *
 * A module may be structured as follows:
 *
 * ~~~
 * yii.sample = (function($) {
 *     var pub = {
 *         // whether this module is currently active. If false, init() will not be called for this module
 *         // it will also not be called for all its child modules. If this property is undefined, it means true.
 *         isActive: true,
 *         init: function() {
 *             // ... module initialization code go here ...
 *         },
 *
 *         // ... other public functions and properties go here ...
 *     };
 *
 *     // ... private functions and properties go here ...
 *
 *     return pub;
Qiang Xue committed
35
 * })(jQuery);
Qiang Xue committed
36 37 38 39
 * ~~~
 *
 * Using this structure, you can define public and private functions/properties for a module.
 * Private functions/properties are only visible within the module, while public functions/properties
40
 * may be accessed outside of the module. For example, you can access "yii.sample.isActive".
Qiang Xue committed
41 42 43
 *
 * You must call "yii.initModule()" once for the root module of all your modules.
 */
Qiang Xue committed
44
yii = (function ($) {
Qiang Xue committed
45 46
    var pub = {
        /**
47
         * List of JS or CSS URLs that can be loaded multiple times via AJAX requests. Each script can be represented
Qiang Xue committed
48 49 50 51 52 53 54 55 56 57 58
         * as either an absolute URL or a relative one.
         */
        reloadableScripts: [],
        /**
         * The selector for clickable elements that need to support confirmation and form submission.
         */
        clickableSelector: 'a, button, input[type="submit"], input[type="button"], input[type="reset"], input[type="image"]',
        /**
         * The selector for changeable elements that need to support confirmation and form submission.
         */
        changeableSelector: 'select, input, textarea',
59

Qiang Xue committed
60 61 62 63 64 65
        /**
         * @return string|undefined the CSRF parameter name. Undefined is returned if CSRF validation is not enabled.
         */
        getCsrfParam: function () {
            return $('meta[name=csrf-param]').prop('content');
        },
66

Qiang Xue committed
67 68 69 70 71 72
        /**
         * @return string|undefined the CSRF token. Undefined is returned if CSRF validation is not enabled.
         */
        getCsrfToken: function () {
            return $('meta[name=csrf-token]').prop('content');
        },
73

74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        /**
         * Sets the CSRF token in the meta elements.
         * This method is provided so that you can update the CSRF token with the latest one you obtain from the server.
         * @param name the CSRF token name
         * @param value the CSRF token value
         */
        setCsrfToken: function (name, value) {
            $('meta[name=csrf-param]').prop('content', name);
            $('meta[name=csrf-token]').prop('content', value)
        },

        /**
         * Updates all form CSRF input fields with the latest CSRF token.
         * This method is provided to avoid cached forms containing outdated CSRF tokens.
         */
        refreshCsrfToken: function () {
            var token = pub.getCsrfToken();
            if (token) {
                $('form input[name="' + pub.getCsrfParam() + '"]').val(token);
            }
        },

Qiang Xue committed
96 97 98 99 100
        /**
         * Displays a confirmation dialog.
         * The default implementation simply displays a js confirmation dialog.
         * You may override this by setting `yii.confirm`.
         * @param message the confirmation message.
101 102
         * @param ok a callback to be called when the user confirms the message
         * @param cancel a callback to be called when the user cancels the confirmation
Qiang Xue committed
103
         */
104 105 106 107 108 109
        confirm: function (message, ok, cancel) {
            if (confirm(message)) {
                !ok || ok();
            } else {
                !cancel || cancel();
            }
Qiang Xue committed
110
        },
111

Qiang Xue committed
112 113 114 115 116 117 118 119 120
        /**
         * Handles the action triggered by user.
         * This method recognizes the `data-method` attribute of the element. If the attribute exists,
         * the method will submit the form containing this element. If there is no containing form, a form
         * will be created and submitted using the method given by this attribute value (e.g. "post", "put").
         * For hyperlinks, the form action will take the value of the "href" attribute of the link.
         * For other elements, either the containing form action or the current page URL will be used
         * as the form action URL.
         *
Qiang Xue committed
121 122
         * If the `data-method` attribute is not defined, the `href` attribute (if any) of the element
         * will be assigned to `window.location`.
Qiang Xue committed
123
         *
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
         * Starting from version 2.0.3, the `data-params` attribute is also recognized when you specify
         * `data-method`. The value of `data-params` should be a JSON representation of the data (name-value pairs)
         * that should be submitted as hidden inputs. For example, you may use the following code to generate
         * such a link:
         *
         * ```php
         * use yii\helpers\Html;
         * use yii\helpers\Json;
         *
         * echo Html::a('submit', ['site/foobar'], [
         *     'data' => [
         *         'method' => 'post',
         *         'params' => [
         *             'name1' => 'value1',
         *             'name2' => 'value2',
         *         ],
         *     ],
         * ];
         * ```
         *
Qiang Xue committed
144 145 146
         * @param $e the jQuery representation of the element
         */
        handleAction: function ($e) {
Qiang Xue committed
147 148
            var method = $e.data('method'),
                $form = $e.closest('form'),
149 150
                action = $e.attr('href'),
                params = $e.data('params');
Qiang Xue committed
151

Qiang Xue committed
152
            if (method === undefined) {
Qiang Xue committed
153 154
                if (action && action != '#') {
                    window.location = action;
155
                } else if ($e.is(':submit') && $form.length) {
156
                    $form.trigger('submit');
Qiang Xue committed
157
                }
158
                return;
Qiang Xue committed
159
            }
160

161
            var newForm = !$form.length;
Qiang Xue committed
162 163 164 165
            if (newForm) {
                if (!action || !action.match(/(^\/|:\/\/)/)) {
                    action = window.location.href;
                }
166 167
                $form = $('<form method="' + method + '"></form>');
                $form.prop('action', action);
Qiang Xue committed
168 169 170 171 172 173
                var target = $e.prop('target');
                if (target) {
                    $form.attr('target', target);
                }
                if (!method.match(/(get|post)/i)) {
                    $form.append('<input name="_method" value="' + method + '" type="hidden">');
Qiang Xue committed
174
                    method = 'POST';
Qiang Xue committed
175
                }
Qiang Xue committed
176 177 178 179 180
                if (!method.match(/(get|head|options)/i)) {
                    var csrfParam = pub.getCsrfParam();
                    if (csrfParam) {
                        $form.append('<input name="' + csrfParam + '" value="' + pub.getCsrfToken() + '" type="hidden">');
                    }
Qiang Xue committed
181 182 183
                }
                $form.hide().appendTo('body');
            }
184

Qiang Xue committed
185 186 187 188 189
            var activeFormData = $form.data('yiiActiveForm');
            if (activeFormData) {
                // remember who triggers the form submission. This is used by yii.activeForm.js
                activeFormData.submitObject = $e;
            }
190

191 192 193 194 195 196 197
            // temporarily add hidden inputs according to data-params
            if (params && $.isPlainObject(params)) {
                $.each(params, function (idx, obj) {
                    $form.append('<input name="' + idx + '" value="' + obj + '" type="hidden">');
                });
            }

Qiang Xue committed
198 199
            var oldMethod = $form.prop('method');
            $form.prop('method', method);
200 201 202 203 204
            var oldAction = null;
            if (action && action != '#') {
                oldAction = $form.prop('action');
                $form.prop('action', action);
            }
Qiang Xue committed
205

Qiang Xue committed
206
            $form.trigger('submit');
207

208 209 210
            if (oldAction != null) {
                $form.prop('action', oldAction);
            }
Qiang Xue committed
211 212
            $form.prop('method', oldMethod);

213 214 215 216 217 218 219
            // remove the temporarily added hidden inputs
            if (params && $.isPlainObject(params)) {
                $.each(params, function (idx, obj) {
                    $('input[name="' + idx + '"]', $form).remove();
                });
            }

Qiang Xue committed
220 221 222 223
            if (newForm) {
                $form.remove();
            }
        },
224

Qiang Xue committed
225 226 227 228 229 230 231 232 233 234 235 236
        getQueryParams: function (url) {
            var pos = url.indexOf('?');
            if (pos < 0) {
                return {};
            }
            var qs = url.substring(pos + 1).split('&');
            for (var i = 0, result = {}; i < qs.length; i++) {
                qs[i] = qs[i].split('=');
                result[decodeURIComponent(qs[i][0])] = decodeURIComponent(qs[i][1]);
            }
            return result;
        },
237

Qiang Xue committed
238 239 240 241 242 243 244 245 246 247 248 249
        initModule: function (module) {
            if (module.isActive === undefined || module.isActive) {
                if ($.isFunction(module.init)) {
                    module.init();
                }
                $.each(module, function () {
                    if ($.isPlainObject(this)) {
                        pub.initModule(this);
                    }
                });
            }
        },
250

Qiang Xue committed
251 252 253 254 255 256 257
        init: function () {
            initCsrfHandler();
            initRedirectHandler();
            initScriptFilter();
            initDataMethods();
        }
    };
258

Qiang Xue committed
259 260 261 262 263 264 265 266 267
    function initRedirectHandler() {
        // handle AJAX redirection
        $(document).ajaxComplete(function (event, xhr, settings) {
            var url = xhr.getResponseHeader('X-Redirect');
            if (url) {
                window.location = url;
            }
        });
    }
268

Qiang Xue committed
269 270 271 272 273 274 275
    function initCsrfHandler() {
        // automatically send CSRF token for all AJAX requests
        $.ajaxPrefilter(function (options, originalOptions, xhr) {
            if (!options.crossDomain && pub.getCsrfParam()) {
                xhr.setRequestHeader('X-CSRF-Token', pub.getCsrfToken());
            }
        });
276
        pub.refreshCsrfToken();
Qiang Xue committed
277
    }
278

Qiang Xue committed
279
    function initDataMethods() {
280
        var handler = function (event) {
Qiang Xue committed
281 282 283 284 285
            var $this = $(this),
                method = $this.data('method'),
                message = $this.data('confirm');

            if (method === undefined && message === undefined) {
286
                return true;
Qiang Xue committed
287
            }
Qiang Xue committed
288

289 290 291 292
            if (message !== undefined) {
                pub.confirm(message, function () {
                    pub.handleAction($this);
                });
Qiang Xue committed
293
            } else {
294
                pub.handleAction($this);
Qiang Xue committed
295
            }
296 297 298 299 300 301 302
            event.stopImmediatePropagation();
            return false;
        };

        // handle data-confirm and data-method for clickable and changeable elements
        $(document).on('click.yii', pub.clickableSelector, handler)
            .on('change.yii', pub.changeableSelector, handler);
Qiang Xue committed
303
    }
304

Qiang Xue committed
305 306 307 308 309
    function initScriptFilter() {
        var hostInfo = location.protocol + '//' + location.host;
        var loadedScripts = $('script[src]').map(function () {
            return this.src.charAt(0) === '/' ? hostInfo + this.src : this.src;
        }).toArray();
310

Qiang Xue committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
        $.ajaxPrefilter('script', function (options, originalOptions, xhr) {
            if (options.dataType == 'jsonp') {
                return;
            }
            var url = options.url.charAt(0) === '/' ? hostInfo + options.url : options.url;
            if ($.inArray(url, loadedScripts) === -1) {
                loadedScripts.push(url);
            } else {
                var found = $.inArray(url, $.map(pub.reloadableScripts, function (script) {
                    return script.charAt(0) === '/' ? hostInfo + script : script;
                })) !== -1;
                if (!found) {
                    xhr.abort();
                }
            }
        });
327 328 329 330 331 332 333 334 335 336 337 338 339 340

        $(document).ajaxComplete(function (event, xhr, settings) {
            var styleSheets = [];
            $('link[rel=stylesheet]').each(function () {
                if ($.inArray(this.href, pub.reloadableScripts) !== -1) {
                    return;
                }
                if ($.inArray(this.href, styleSheets) == -1) {
                    styleSheets.push(this.href)
                } else {
                    $(this).remove();
                }
            })
        });
Qiang Xue committed
341
    }
342

Qiang Xue committed
343
    return pub;
Qiang Xue committed
344
})(jQuery);
Qiang Xue committed
345

Qiang Xue committed
346
jQuery(document).ready(function () {
Qiang Xue committed
347
    yii.initModule(yii);
Qiang Xue committed
348
});