views:

38

answers:

1

I'm attempting to write my first jQuery plugin to query multi-dimensional arrays of complex objects. It kind of functions how I want it, but right now it receives a property name and value as input for comparison of the items. I want to modify it so that it can receive jQuery's selector syntax as input in order to filter my objects in a more encompassing manner.

I want to be able to provide syntax the same as or similar to jquery's 'native' selector syntax:

"string"
"number"
"boolean"
"object"
"string,number,boolean"
"object[FirstName='Ben'][LastName='Alabaster']"
"object[LastName^='Ala']"
"object[LastName$='er']"

etc.

Are there any tutorials or plugins that demonstrate this ability to parse selector syntax for comparing against objects?

+3  A: 

The selector syntax that jQuery uses was abstracted into the Sizzle library. you can view the source to Sizzle on GitHub.

Sizzle is pretty clearly customized to query against a document's Document Object Model, so you'd be doing modifications to get it to query against other kinds of data. Have a look at lines 294 to 303:

match: {
    ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
    CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
    NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
    ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
    TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
    CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
    POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
    PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},

And here's code that appears to parse attribute selectors like ^= and ~=, lines 661 to 691:

ATTR: function(elem, match){
    var name = match[1],
        result = Expr.attrHandle[ name ] ?
            Expr.attrHandle[ name ]( elem ) :
            elem[ name ] != null ?
                elem[ name ] :
                elem.getAttribute( name ),
        value = result + "",
        type = match[2],
        check = match[4];

    return result == null ?
        type === "!=" :
        type === "=" ?
        value === check :
        type === "*=" ?
        value.indexOf(check) >= 0 :
        type === "~=" ?
        (" " + value + " ").indexOf(check) >= 0 :
        !check ?
        value && result !== false :
        type === "!=" ?
        value !== check :
        type === "^=" ?
        value.indexOf(check) === 0 :
        type === "$=" ?
        value.substr(value.length - check.length) === check :
        type === "|=" ?
        value === check || value.substr(0, check.length + 1) === check + "-" :
        false;
},

The way these regular expressions and logic are used may give you ideas as to how to implement your data structure queries.

artlung
I think I need to come back to this when I'm not half asleep :P Thanks
BenAlabaster