Code coverage report for lib/locator.js

Statements: 100% (24 / 24)      Branches: 100% (2 / 2)      Functions: 100% (5 / 5)      Lines: 100% (24 / 24)      Ignored: none     

All files » lib/ » locator.js
1 2 3 4 5 6 7 8 9 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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114                    1 1 1 1 1               1 2     1                     2   2                           1   1                               3   2   2   1   1           1   1       1                         1   1   1       1  
/**
 * @file 定位器
 *
 * 负责提供客户端上的url变化事件
 * 还可以通过pushState添加历史记录,修改location
 *
 * @author Leon(leon@outlook.com)
 * @module locator
 */
 
var events = require('./events');
var env = require('./env');
var Emitter = require('./Emitter');
var invariant = require('./util/invariant');
var url = require('./url');
 
/**
 * 当前客户端是否支持历史api
 *
 * @private
 * @return {boolean}
 */
function isHistorySupported() {
    return !!window.history;
}
 
var locator = {
 
    /**
     * 开始侦听浏览器的前进/后退事件
     *
     * @public
     * @method module:locator.start
     * @return {module:locator}
     */
    start: function () {
 
        window.onpopstate = onHistoryChange;
 
        return this;
 
    },
 
 
    /**
     * 停止浏览器的前进/后退事件
     *
     * @public
     * @method module:locator.stop
     * @return {module:locator}
     */
    stop: function () {
 
        window.onpopstate = null;
 
        return this;
 
    },
 
    /**
     * 对当前页面进行跳转操作
     *
     * @public
     * @method module:locator.redirect
     * @param {!string} path 跳转到的新地址
     * @param {?Object} query query参数
     * @return {boolean} 是否是pushState跳转
     * @fires module:events~locator.redirect
     */
    redirect: function (path, query) {
 
        invariant(env.isClient, 'redirect cannot run on server');
 
        var uri = url.makeUrl(path, query);
 
        if (isHistorySupported()) {
 
            events.emit('locator.redirect');
 
            history.pushState(
                null,
                window.title,
                uri
            );
 
            this.emit('redirect', path, query);
 
            return true;
 
        }
 
        return false;
 
    }
 
};
 
/**
 * 页面发生了前进/后退事件处理函数
 *
 * @private
 * @param {Object} e popstate事件
 * @fires module:locator~redirect
 */
function onHistoryChange(e) {
 
    var uri = url.parse(location.href);
 
    locator.emit('redirect', uri.path, uri.query);
 
}
 
module.exports = Emitter.enable(locator);