Thymeleaf, Javascript Inlining And Iteration
Solution 1:
I'll accept your invitation for new ideas and put on the table my methodology of approaching similar cases. Clearly the problem is mostly about the communication between back-end and javascript data. The data that the javascript function needs as an argument in this case. Since html5's introduction of data attributes and the improved jQuery's efficiency with them in late versions, you may expose whatever back end data you want as attributes starting with "data-". This is valid according to html5. In jQuery you can access them as if they were jQuery data by translating the html naming convention to camelCase after reducing the initial "data-" pefix. (e.g. data-my-attribute = myAttribute). You can either access them in the original html convention (e.g. my-attribute). Its a matter of preference.
Then your html can be much cleaner:
<td th:each="optionValue,iterStat : ${someObject.optionValues}">
<button class="btn btn-default" th:id="${'optionBtn_' + (iterStat.count - 1)}" th:text="${optionValue.toString()}" th:attr="data-my-func-attr=${optionValue}"/>
</td>
You can bind your event handlers then as:
$("button.btn").on("click", function() {
buttonPressed($(this).data("my-func-attr"))
}
or similar.
This way you also keep your code cleaner and separate from the markup which is one principle of Unobtrusive JS
Solution 2:
So I have made a workaround.
Because multiple elements can exist in a page I simply create an outer loop of the tag and create one for each button. The details in the method call will have the same index/text mapping as in the iteration to create the buttons in the first place, although the text creation was a bit tricky:
<script th:each="optionValue,iterStat : ${someObject.optionValues}">
$([[${'#optionBtn_' + (iterStat.cont - 1)}]]).on("click", function() {
buttonPressed([[${iterStat.count - 1}]], [[${estimateOption.toString()}]]);
});
</script>
Not the smallest once the code is generated, but it works.
Post a Comment for "Thymeleaf, Javascript Inlining And Iteration"