Binding Array of Objects to kendo listview

1k Views Asked by At

I have a case where my ViewModel has an Array such as,

{id: 0,
 Name: "KendoListView1",
 dataitems: [{id: 1, itemName: "Kendo"}, {id: 2, itemName: "List"}]
},

{id: 2,
 Name: "KendoListView2",
 dataitems: [{id: 3, itemName: "Kendo"}, {id: 4, itemName: "List"}]
}, 

{id: 3,
 Name: "KendoListView3",
 dataitems: []
}

So now when I bind my ViewModel to the ListView template, my template needs to handle the case where, if there is an Array I show the Array elements in the view, and when the Array is empty I just need to show the Name (KendoListView1, KendoListView2) and not the Array elements

I need a template structure like this:

<script id="template" type="text/kendo-ui-template">  
# if(dataitems.length) { #
    <div>
         //Show all the items Names from the Array
    </div>
# } else {#
    <div>
         //Show all the Names
    </div>
# } #
</script>

I tried to iterate through the Array using a for loop and display the items when I have an Array, but in runtime, once I add a new item into the Array, the for loop would run through all the items again and display all items.

Can anyone help me in this case

1

There are 1 best solutions below

0
On

A .Map().Join() can be used for rendering your sometimes filled dataitems.

Template

  <script id="my_funky_listview_template" type="text/x-kendo-template">
    <div>
    # if (dataitems.length) { #
      #:
        itemName + " items: " + dataitems.map(function(item){return item.itemName;}).join(",")
      #
    # } else { #
      #:
        Name
      #
    # } #
    </div>
  </script>

Declaration / configuration

<script>
$(function() {
  $("#listview").kendoListView({
    dataSource: dataSource,
    template: kendo.template($("#my_funky_listview_template").html())
  });     
});
</script>

If the data source delivers any content that is missing a Name or dataitems property the javascript console will log a '<property>' is not defined. message and the listview will not appear.