从数据属性解析字符串作为对象

时间:2013-06-07 13:17:56

标签: javascript object

我在使用jQuery validate插件时遇到了很多麻烦,我可以解决它的唯一方法就是使用.submitHandler属性并在其中做一些技巧。

在其上检查触发器的父节点是否为字段集,如果它具有data-submit-handler属性,它将执行我在那里发送的任何内容。

它看起来像这样:

<fieldset data-submit-handler="SITE.Products.QA.Bindings.post">

在这种情况下,SITE.Products.QA.Bindings.post将是一个函数。问题是我不知道如何将数据属性中的字符串解析为对象而不是字符串,因此我可以执行我引用的函数。有办法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用将解决它的帮助程序:

// convert string representation of object in to object reference:
// @p: object path
// @r: root to begin with (default is window)
// if the object doesn't exist (e.g. a property isn't found along the way)
// the constant `undefined` is returned.
function getObj(p, r){
    var o = r || window;
    if (!p) return o;                      // short-circuit for empty parameter
    if(typeof p!=='string') p=p.toString();// must be string
    if(p.length==0) return o;              // must have something to parse
    var ps = p.replace(/\[(\w+)\]/g,'.$1') // handle arrays
              .replace(/^\./,'')           // remove empty elements
              .split('.');                 // get traverse list
    for (var i = 0; i < ps.length; i++){
        if (!(ps[i] in o)) return undefined; // short-circuit for bad key
        o = o[ps[i]];
    }
    return o;
}

// couple extensions to strings/objects

// Turns the string in to an object based on the path
// @this: the string you're calling the method from
// @r: (optional) root object to start traversing from
String.prototype.toObject = function(r){
    return getObj(this,r);
};

// Retrieves the supplied path base starting at the current object
// @this: the root object to start traversing from
// @s: the path to retrieve
Object.prototype.fromString = function(p){
    return getObj(p,this);
};

所以,示例用法:

window.foo = {
    bar: {
        baz: {
            hello: 'hello',
            world: function(){
                alert('world!');
            }
        }
    },
    list: [
        {item: 'a'},
        {item: 'b'},
        {item: 'c'}
    ]
};

var a = 'foo.bar.baz.hello';
console.log(getObj(a));    // hello
console.log(a.toObject()); // hello

var b = 'foo.bar.baz.world';
console.log(getObj(b)());  // world

var c = 'baz.hello';
console.log(getObj(c, foo.bar)); // hello
console.log(foo.bar.fromString(c)); // hello
console.log(c.toObject(foo.bar)); // hello

var d = 'foo.list[1].item';
console.log(getObj(d)); // b