将字符串解析为来自data属性的对象

parse a string as an object from data attribute

本文关键字:data 属性 对象 字符串      更新时间:2023-09-26

我有很多麻烦与jQuery验证插件和唯一的方法,我可以工作围绕它是通过使用.submitHandler属性和做一些技巧里面。

其中一个是检查触发器的父是否是一个字段集,如果它有一个data-submit-handler属性,它将执行我发送的任何东西。

它看起来像这样:

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

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

您可以使用帮助器来解析它:

// 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