jQuery UI tabs

https://groups.google.com/d/topic/knockoutjs/L-437Dk4okQ/discussion

by kougiland

HTML

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css">
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.debug.js"></script>
    <div data-bind="jqTabs: tabs">
        <ul data-bind="foreach: tabs">
            <li>
                <a href="#tab-${id}" data-bind="text: title, attr: { href: '#tab-' + id() }"></a> 
            </li>
        </ul>
        <!-- ko foreach: tabs -->
        <div data-bind="attr: { id: 'tab-' + id() }">
            <h2 data-bind="text: id() + ' - ' + title()"></h2>
            <p data-bind="text: content"></p>
        </div>
        <!-- /ko -->
    </div>


<button data-bind="click: addTab">Add Tab</button>

CSS

h2 { font-weight: bold; font-size: 1.2em; }

JavaScript

ko.bindingHandlers.jqTabs = {
    update: function(element, valueAccessor, allBindingsAccessor) {
       var dependency = ko.utils.unwrapObservable(valueAccessor()),
           currentIndex = $(element).tabs("option", "selected") || 0,
           config = ko.utils.unwrapObservable(allBindingsAccessor().jqTabOptions) || {};
        
        //make sure that elements are set from template before calling tabs API
        setTimeout(function() { 
            $(element).tabs("destroy").tabs(config).tabs("option", "selected", currentIndex);
       }, 0);
    }
};


function Tab(id, title, content) {
    this.id = ko.observable(id);
    this.title = ko.observable(title);
    this.content = ko.observable(content);
}

var viewModel = {
    tabs: ko.observableArray([new Tab(1, "one", "one content"), new Tab(2, "two", "two content"), new Tab(3, "three", "three content")]),
    addTab: function() {
       var newId = this.tabs().length + 1;
       this.tabs.push(new Tab(newId, "new" + newId, "new content" + newId));   
    }
};

ko.applyBindings(viewModel);