Search code examples
data-bindingknockout.jsjquery-mobile-collapsible

Data-Bind List-View using Knockout inside a Collapsible Set


I want to have a list view inside a collapsible-set and I want to bind the data to the list view using knockout.js. Please can anyone help me regarding this with a simple example. I want to bind data in place of Content 1, Content 2 and Content 3 of the below code.

<div data-role="collapsible-set" data-collapsed="false" data-icon="" data-expanded-icon="carat-u" data-collapsed-icon="carat-d" data-iconpos="right">
                <div data-role="collapsible">
                    <h3>Collapsible 1</h3>
                    <div data-role="listview">
                        <p>Content 1</p>
                    </div>

                </div>
                <div data-role="collapsible">
                    <h3>Collapsible 2</h3>
                    <div data-role="listview">
                        <p>Content 2</p>
                    </div>
                </div>
                <div data-role="collapsible">
                    <h3>Collapsible 3</h3>
                    <div data-role="listview">
                        <p>Content 3</p>
                    </div>
                </div>
            </div>

Solution

  • Some specifics regarding the javascript structure to which the knockout binds is not provided, thus I'll have to provide a very generic example.

    Assuming the collapsible elements are part of an array and the listview contents belonging to each are a property:

    Javascript

    Object to represent a collapsible element:

    var Section = function(title, content){
      return {
              title: title,
              content: content, 
              listViewData: new List(title)
            }
    }
    

    where List is just a function to populate an array with "dummy" data.

    var List = function(title){
      var temp = [];
      for(var i = 0; i < 3; i++)
      {
        temp.push({text: title + ': ' + i})
      }
      return temp;
    }
    

    Setup the collapsible behavior, ensuring the call is after applyBindings:

     ko.applyBindings(modelInstance)
     $("div[id^='collapsible']").collapsible()
    

    HTML

    <div class="ui-body-d tablist-content" data-role="collapsible-set" data-bind='foreach: items'>
     <div data-bind="attr: {'id': 'collapsible-'+ $index}">
        <h3 data-bind='text: title'></h3>
    
        <p> <span data-bind='text: content'></span>
    
         <ul data-role="listview" data-bind="foreach: { data: listViewContents, as: 'listItem'}">
           <li><a href="#" data-bind="text: listItem.text"></a></li>
         </ul>
    
        </p>
    </div>