This is a short example of how to use the foreach functionality in CommonHIT. Please inspect this document's source code to see how certain functionality is being achieved.
Any container with the CSS class hit-foreach
will act as a template
and will be instantiated multiple times (without the wrapping container):
The script in commonhit.js
will call a global function
(specified by the user in the data-func
attribute)
to obtain an array of objects
[x_1, x_2, ..., x_n]
.
Then for each object, the script will instantiate the template for each object
x_i
by replacing each
{{field}}
in the template with
x_i[field]
.
Sometimes you want the order of the list to be random.
This can be achieved by using HIT.shuffleArray(array)
.
This function shuffles the original array in place.
The return value of the function is the shuffled array:
Templates can be given an id
,
such that you can add new instances within a script:
window.counter = (window.counter || 0) + 1; HIT.Template.byId['scriptedForeach'].addItem({ value: counter, label: 'Vote for ' + counter }); HIT.generateIdNames($('#ScriptedList'));
It is also possible to get them byNode:
window.counter2 = (window.counter2 || 0) + 1; HIT.Template.byNode(document.getElementById('scriptedForeach2')).addItem({ value: counter2, label: 'Vote for ' + counter2 }); HIT.generateIdNames($('#ScriptedList2'));