Kendo UI for loop data binding
-
21-12-2019 - |
Question
I have such a code in my project:
<script id="menuTemplate" type="text/x-kendo-template">
# for(var i=0; i < menus.menu.length; i++){ #
<li id="menu-#= i#" data-bind="events: {click: menuClick}" class="menu-item">
<div>#= menus.menu[i].name #</div>
</li>
# } #
</script>
<div data-role="view" id="menuPage" data-model="menuViewModel">
<ul id="menuListView" data-role="listview" data-template="menuTemplate" data-bind="source: dataSource"></ul>
</div>
<script>
$(document).ready(function(){
var dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "data/test.json",
dataType: "json",
},
},
schema: {
data: function(data) {
return data;
}
},
});
var menuViewModel = kendo.observable({
dataSource: dataSource,
menuClick: function(e) {
alert(e);
}
});
kendo.bind($(document.body), menuViewModel);
});
</script>
So I have listview Items and I want bind clicks on them. The problem is that click binds only to the first element of the listview, so alert fires only when I click to the element with the "menu-0" id. What I write wrong and how bind the handler properly so menuClick function will be handler for all listview items?
Thanks in advance!
Solution
Wrapping list items into div solves the issue:
<script id="menuTemplate" type="text/x-kendo-template">
<div>
# for(var i=0; i < menus.menu.length; i++){ #
<li id="menu-#= i#" data-bind="events: {click: menuClick}" class="menu-item">
<div>#= menus.menu[i].name #</div>
</li>
# } #
</div>
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow