jQuery UI accordion

https://groups.google.com/d/topic/knockoutjs/h97sy04PK10/discussion

by spring1975

HTML

<script src="http://knockoutjs.com/downloads/knockout-2.3.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/themes/black-tie/jquery-ui.css">
<div data-bind="foreach: items, accordion: {}">
    <h3>
        <a href="#" data-bind="text: id"></a>
    </h3>
    <div>    
        <span data-bind="text: name"></span>
        <div data-bind="foreach: $root.items, accordion: {}">
            <h3>
                <a href="#" data-bind="text: id"></a>
            </h3>
            <div data-bind="text: name">    
            </div> 
        </div>
    </div> 
</div>
<button data-bind="click: add">Add Item</button>
<hr/>

JavaScript

ko.bindingHandlers.accordion = {
    init: function(element, valueAccessor) {
        var options = valueAccessor() || {};
        setTimeout(function () {
                $(element).accordion(options);
            }, 0);
        
        
        //handle disposal (if KO removes by the template binding)
          ko.utils.domNodeDisposal.addDisposeCallback(element, function(){
              $(element).accordion("destroy");
          });
    },
    update: function(element, valueAccessor) {
        var options = valueAccessor() || {};
        $(element).accordion("destroy").accordion(options);
    }
}

function Item(id, name) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
}

var viewModel = {
    items: ko.observableArray(),
    add: function() {
        viewModel.items.push(new Item(4, "foo"));
    }
};

ko.applyBindings(viewModel);

setTimeout(function() {
    viewModel.items([
        new Item(1, "one"),
        new Item(2, "two"),
        new Item(3, "three")]);
    $(document).append('hi');
}, 2000);