RequireJS中“localstorage”的原型

时间:2014-08-27 17:31:03

标签: javascript requirejs

我目前已经为“localStorage”添加了一些方法。

/**
 *
 * MOVED TO: https://github.com/iFind/html5MultidimensionalStorage
 *
 * This methods extends the default HTML5 Storage object and add support
 * to set and get multidimensional data
 *
 * @example Storage.setObj('users.albums.sexPistols',"blah");
 * @example Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
 * @example Storage.setObj('users.albums.sexPistols.sid',"Other songs");
 *
 * @example Storage.getObj('users');
 * @example Storage.getObj('users.albums');
 * @example Storage.getObj('users.albums.sexPistols');
 * @example Storage.getObj('users.albums.sexPistols.sid');
 * @example Storage.getObj('users.albums.sexPistols.nancy');
 *
 * This is just a prototype and is not recommended to use at production apps
 * USE AT YOUR OWN RISK
 *
 * @author Klederson Bueno <klederson@klederson.com>
 * @author Gabor Zsoter <helo@zsitro.com>
 */
//Add Storage support for objects
Storage.prototype.__walker = function(path,o) {
    //Validate if path is an object otherwise returns false
    if(typeof path !== "object")
    return undefined;

    if(path.length === 0){
    return o;
    }

    for(var i in path){
    var prop = path[i];
    //Check if path step exists
    if(o.hasOwnProperty(prop)){
        var val = o[prop];
        if(typeof val == 'object'){
        path.splice(0,1);
        return this.__walker(path,val);
        } else {
        return val;
        }
    }
    }
};

Storage.prototype.setObj = function(key, value) {

    var key = encodeURIComponent(key);

    var path = key.split('.');

    //First level is always the localStorage key pair item
    var _key = path[0];
    var os = this.getItem(_key) !== null ? JSON.parse(this.getItem(_key)) : null; //general storage key pair element
    path.splice(0,1);

    if(os === null) {
    os = {};
    this.setItem(_key,JSON.stringify(os));
    }

    var innerWalker = function(path,o) {

    //Validate if path is an object otherwise returns false
    if(typeof path !== "object")
        return undefined;

    if(path.length == 1) {
        o[path[0]] = value;
        return o;
    } else if(path.length === 0) {
        os = value;
        return os;
    }

    var val = null;

    for(var i in path){
        var prop = path[i];
        //Check if path step exists
        if(o.hasOwnProperty(prop)) {
        val = o[prop];
        if(typeof val == 'object'){
            path.splice(0,1);
            return innerWalker(path,val);
        }
        } else {
        //create depth
        o[prop] = {};
        val = o[prop];
        path.splice(0,1);
        return innerWalker(path,val);
        }
    }
    };

    innerWalker(path,os);

    this.setItem(_key,JSON.stringify(os));
};

Storage.prototype.getObj = function(key) {

    var key = encodeURIComponent(key);
    key = key.split('.');

    //First level is always the localStorage key pair item
    var _key = key[0];
    var o = this.getItem(_key) ? JSON.parse(this.getItem(_key)) : null;

    if(o === null)
    return undefined;

    key.splice(0,1);

    return this.__walker(key,o);
};

在另一堂课中,我这样做:

define(['jquery', '_Errors'], function($, Errors) {
[...]

    localStorage.getObj('blabla');

[...]
});

在我迁移到RequireJS之前,我只是将所有函数/原型放在一个名为functions.js的文件中 - 这还有可能吗?或者我是否需要指定我将在每个文件中使用的所有函数?

1 个答案:

答案 0 :(得分:1)

您有两种常规选择来加载functions.js文件:

  1. 加载修改RequireJS的Storage 的文件。这意味着将它放在自己的script元素中。我会在加载之前加载它,以便RequireJS加载的所有内容都会受益于此文件所做的更改。

  2. 让RequireJS加载functions.js。您需要以下配置:

    paths: {
        functions: "path/to/functions.js"
    },
    shim: {
        functions: {
            // This should be something that only your file creates.
            // In some circumstances it is used by RequireJS to check whether something
            // has loaded.
            exports: 'Storage.prototype.getObj'
        }
    }
    

    但是每个模块你需要使用functions添加的函数需要在其依赖项中列出它:

    define(['jquery', '_Errors', 'functions'], function ($, Errors) {
        [...]
    
        localStorage.getObj('blabla');
    
        [...]
    });
    
  3. 每当我加载进行修改的内容时,就会开始修改ElementNodeStorage等内容,我更喜欢使用上面的第一个选项。我希望首先加载所有这些,以便之后的所有内容都能看到相同的环境。因此它全部加载在RequireJS之外。如果您发现性能因为加载了大量这些小文件而成为一个问题,那么您始终可以自定义优化步骤以连接这些文件,并在r.js生成的包的开头添加它们。