write-search.js 1.26 KB
/**
 * 将搜索结果存localStorage
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/29
 */

var ranToken = ' ??++ ';

function isLocalStorageSupported() {
    var testKey = 'test',
        storage = Window.prototype.localStorage;

    try {
        storage.setItem(testKey, 'testValue');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

//获取分隔符
function getRanToken() {
    return ranToken;
}

//绑定提交前的存local操作
function bindWirteLocal($form) {
    $form.on('submit', function() {
        var query = this.query.value,
            historys;

        if (localStorage) {
            if (isLocalStorageSupported()) {
                historys = localStorage.getItem('historys');
            }

            historys = historys ? historys : '';

            if (historys.indexOf(ranToken + query + ranToken) > -1) {
                return;
            }

            if (historys === '') {
                query = ranToken + query;
            }

            historys += query + ranToken;
            if (isLocalStorageSupported()) {
                localStorage.setItem('historys', historys);
            }
        }
    });
}

exports.getRanToken = getRanToken;

exports.bindWirteLocal = bindWirteLocal;