views:

80

answers:

3

Hi,

As you know, a single String can define many key/value properties. For instance, a query String can be defined as

someKey=someValue&anotherKey=anotherValue

Now i need to define a pattern in which a single String can define many key/value properties to be stored in a class attribute. But each value can be a String, an Array, A reference to a JavaScript function etc. Something like (Hypothetical pattern)

class="p=[1,2,3,4]&a=aaa&c=f()"

Its purpose: post-processing input Field through class atribute

Any advice to define a good pattern ?

+4  A: 

You might want to look into Javascript Object Notation (JSON) at http://www.json.org/.

It describes basically what you are looking for, and is an industry standard way of packaging data nicely, so you won't be alone in using it.

EDIT: Given that the problem requires function references and/or runtime evaluation of functions, and that the whole thing is meant to be wrangled into a double quoted html class attribute, I second Gumbo's answer of just using javascript.

Clueless
Good, But how can i define a good pattern to define a reference to a JavaScript function by using JSON ? Any advice ?
Arthur Ronald F D Garcia
-1 JSON does not allow function references.
Gumbo
A: 

Here is a string formatted as JSON:

var dataString = "'FirstName' : 'David', 'LastName' : 'Robbins', 'Dates' : {'BirthDate' : '12/12/1966', 'Graduated': '6/21/1984'}"

You can de-serialize the string to a Javascript object with the following call:

var userData = eval("(" + dataString +")");

You could natrually wrap the eval in another function.

David Robbins
Again: JSON does not know functions references nor functions.
Gumbo
+3  A: 

The easiest would be to use plain JavaScript:

attr="p=[1,2,3,4];a='aaa';c=f"

Note that c=f() is not assigning the function f to c but the return value of the function f. c=f is assigning the function f to c.

You can evaluate that code with eval:

eval(element.getAttribute("attr"));
Gumbo
The term "reference" is misleading imo. The value of c is the function that is also the value of f. No need to de-reference it to get the function.
Alsciende