Question

currently i have the "new item form" for my application. i used mustacheJS for it's template. there are some fields which need data from a database, sent via ajax. like for example, a certain select box.

<select name="customerOrder">
    {{#order}} <option value="{{id}}">{{itemName}}</option> {{/order}}
</select>

the data to fill this up with items would look like this:

{
    "order": [
        {
            "id":1,
            "itemName":"Meat Lover's Pizza"
        }, //and so on...
    ]
}

works fine until i am about to create the edit form, where, besides the form data to fill the select boxes and check boxes, i now have to mark the form elements as selected. however...

the item data is retrieved on another ajax call, hence another JSON object. i can't necessarily merge because data might be of different structures. i could have tried this approach but this meant that form data and item data would be "one" - i don't want that. i want a clear separation of the tangible data, and the non-tangible data

the item data looks like this basically, but may be nested somewhere in the JSON object:

{
    "customer":"mario",
    "order": 1          --> this item i want selected in the form
    //and so on...
}

if there was only some way to build the form, after that, populate and mark it seamlessly while still using mustache JS. i don't want to hard code the data with their corresponding form fields.

i heard about runtime rendering and partials, but i can't seem to see how i'd use them for this.

Was it helpful?

Solution

I figured it out! I got the idea from using "inverted sections" in mustache.

The one i did above seemed like a dead-end or if I pursued it, I'd be complicating everything.

What I did was:

  1. Instead of having ajax send over the values for <option> and have a template for filling them in the <select>, i had my template built on the server side and fill the <select>'s options with the data. Additionally, i used the template as "markers" for selected item.

  2. The only thing to fetch via ajax will be the the item data. I altered the structure of the JSON object to fit with the built template. Instead of handing over data, I instead, handed over "markers"

The end result:

//build from the server-side ready with options, and with "markers

<select name="customerOrder">
    <option value="1" {{#order}}{{#i1}}selected="selected"{{/i1}}{{/order}}>Meat Lover's Pizza</option>
    <option value="2" {{#order}}{{#i2}}selected="selected"{{/i2}}{{/order}}>Supreme</option>
</select>

//JSON "edit-mode" data

{
    "order": {
        "i2":true // this will render the "selected" attribute on the one with "i2"
    }             // refer to "non-empty" list and "inverted sections"
}                 // http://mustache.github.com/mustache.5.html
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top