Search code examples
javascriptjqueryjtemplates

Passing an associative array to jTemplates as a parameter


I've created a jTemplate to display an array of "test" objects. The array is a regular indexed array. The template is very basic, just uses a {#foreach} to iterate through the items in the array and displays them in a small table. This template dos the job and I get the expected output.

    // Setup the JTemplate. 
    $('#tests_div').setTemplate($('#tests_template').html());

    try {

        // Process the JTemplate to display all currently selected tests.
        $('#tests_div').processTemplate(_selectedTests);
    }
    catch (e) {
        alert('Error with processing template: ' + e.Description);
    }


    <script type="text/html" id="tests_template">
       {#foreach $T as tests}
          <table>
             <tr>
                <td>Index: {$T.tests.index}</td>
                <td>Name: {$T.tests.firstname} {$T.tests.lastname}</td>
                <td>Score: {$T.tests.score} </td>
             </tr>
          </table>
      {#/for}
    </script>

What I'd like to do is change my array to be an associative array and store my objects in it using the test's index. This makes it easier to work with when I need to do some manipulation of the tests later on.

var a = new Test;
a.index = 12345678;
_selectedTests[a.index] = a;

However, when I pass the array to the template, I get an error about the script is causing my browswer to run slow, asking if I would like to stop it. It seems like its in some kind of endless loop. I'm not sure the template is reading the array correctly. Can anyone tell me how I work with the associative array inside the jTemplates?


Solution

  • You issue is that your array thinks it is huge:

    _selectedTests[12345678] = a; // creates an array of 12345678 elements!! length of 12345678
    

    so you can do this:

    _selectedTests[a.index.toString()] = a; // creates an associative array with one key "12345678", length of 1