简体   繁体   中英

How can I include a Javascript string constructor in a JSON string?

I'm building a template to Jquery Mobile listviews. To make the template fully generic, I need to pass the listitem text. So currently my listview config looks like this:

<ul data-role="listview" data-create="false" class="template" data-config='{
    "type":"listview",
    "data":"getRetailers",
    "custom_classes":["embedded_filter updateResults f-875","nMT pickList f-875 widget_listview","f-n",""],
    "lib":"static_listview.html",
    "tmp":"tmp_listview_inset",
    "lang":"locale_search",
    ...
    }'></ul>

My problem is how to include a Javascript constuctor for the list item text. This should be the following:

inv.company+', '+ inv.zip + ', ' + inv.city

But inserting it like this:

...
"text":"inv.company+', '+ inv.zip + ', ' + inv.city"
}

does not work.

Question :
How to include Javascript constructors in JSON?

试试这个代码:

"text":"'"+ inv.company+ "', '"+ inv.zip + "','" + inv.city+ "'";

Ok. Not nice, but working:

1) In my JSON I'm only passing a function name like so:

<ul data-role="listview" data-create="false" class="template" data-config='{  
    "type":"listview",
    "data":"getRetailers",
    "custom_classes":["embedded_filter updateResults f-875","nMT pickList f-875 widget_listview","f-n",""],
    "lib":"static_listview.html",
    "tmp":"tmp_listview_inset",
    "lang":"locale_search",
    "text":"buildRetailers",
    ...
}'></ul>

2) Then in my script I'm adding buildRetailers to my dynoData module:

var dynoData = {
    ...
    buildRetailers: function (inv) {
        return inv.company+', '+ inv.zip + ', '+ inv.city;
    },
    ...
}

3) And call this from my listview string builder:

....
listItem = listItem.replace( widget.options.re_theme, li_theme );
listItem = listItem.replace( widget.options.re_iconpos, li_iconpos );
listItem = listItem.replace( widget.options.re_icon, li_icon );
// call the function to return the list item text
listItem = listItem.replace( widget.options.re_text, dynoData[ li_text ](inv) );

So I can't seem to pass the function string in the JSON configuration so I need to add a function to construct what I need. If someone knows a better way please post. I will test and check.

Can't you just pass what the object literal version of the inv object is.

"text" : {
    "company": "some value here",
    "zip": "another value here",
    "city": "another value"
}

Normally you would do it like this:

"text": function(){ return inv.company+', '+ inv.zip + ', ' + inv.city }

But I'm not sure if it ever works. You can try it anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM