Skip to content Skip to sidebar Skip to footer

Keep Track Of Tabs With Knockoutjs + Twitter Bootstrap

I'm trying to keep track of the selected tab in the view model but I can't seem to make it work. In the following code when you click a tab the header will update correctly but the

Solution 1:

There are several ways that you can handle this either using bootstrap's JS or by just having Knockout add/remove the active class.

To do this just with Knockout, here is one solution where the Section itself has a computed to determine if it is currently selected.

var Section = function (name, selected) {
    this.name = name;
    this.isSelected = ko.computed(function() {
       return this === selected();  
    }, this);
}

var ViewModel = function () {
    varself = this;

    self.selectedSection = ko.observable();

    self.sections = ko.observableArray([
        new Section('One', self.selectedSection),
        new Section('Two', self.selectedSection),
        new Section('Three', self.selectedSection)
    ]);

    //inialize to the first sectionself.selectedSection(self.sections()[0]);
}

ko.applyBindings(new ViewModel());

Markup would look like:

<divclass="tabbable"><ulclass="nav nav-tabs"data-bind="foreach: sections"><lidata-bind="css: { active: isSelected }"><ahref="#"data-bind="click: $parent.selectedSection"><spandata-bind="text: name" /></a></li></ul><divclass="tab-content"data-bind="foreach: sections"><divclass="tab-pane"data-bind="css: { active: isSelected }"><spandata-bind="text: 'In section: ' + name" /></div></div></div>

Sample here: http://jsfiddle.net/rniemeyer/cGMTV/

There are a number of variations that you could use, but I think that this is a simple approach.

Here is a tweak where the active tab used the section name as a template: http://jsfiddle.net/rniemeyer/wbtvM/

Post a Comment for "Keep Track Of Tabs With Knockoutjs + Twitter Bootstrap"