Suppose I have knockout.js template like this:
<script type="text/html" id="mytemplate">
<label for="inputId">Label for input</label>
<input type="text" id="inputId" data-bind="value: inputValue"/>
</script>
If I render this template in several places on the page I end up with several inputs with the same id (and several labels with the same for value), which has bad consequences. In particular, all code that depends on ids may not work properly (in my case I use jquery.infieldlabel plugin that gets confused by multiple inputs with the same id). The way I solve this issue now is I add unique id attribute to the model that I bind to the template:
<script type="text/html" id="mytemplate">
<label data-bind="attr: {for: id}>Label for input</label>
<input type="text" data-bind="attr: {id: id}, value: inputValue"/>
</script>
This works, but it's not very elegant since I have to have this artificial id attribute in my models that is not used for anything else. I wonder if there is a better solution here.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…