Bootstrap Tabs に Knockout.js と Ajax でデータを表示

Bootstrap Tabs に Knockout.js を使ってデータを表示し、表示するデータは都度サーバーから取得してみます。

HTML部分

<div class="row" id="tabs">
    <div class="col-md-12">
        <ul class="nav nav-tabs">
            <li class="active"><a href="#" data-toggle="tab" data-no="0">Menu 1</a></li>
            <li><a href="#" data-toggle="tab" data-no="1">Menu 2</a></li>
            <li><a href="#" data-toggle="tab" data-no="2">Menu 3</a></li>
        </ul>
        <div class="tab-content" data-bind="foreach: sections">
            <div class="tab-pane" data-bind="css: { active: isSelected }">
                <ul data-bind="foreach: items">
                    <li><a data-bind="attr: { href: Url }"><span data-bind="text: Text"></span></a></li>
                </ul>
            </div>
        </div>
    </div>
</div>

 

で、JavaScript

(function () {
    var section = function (data, selected) {
        this.items = data;
        this.isSelected = ko.computed(function () {
            return this === selected();
        }, this);
    }

    var viewModel = function () {
        var self = this;

        self.selectedSection = ko.observable();

        self.sections = ko.observableArray([
            new section(ko.observableArray(), self.selectedSection),
            new section(ko.observableArray(), self.selectedSection),
            new section(ko.observableArray(), self.selectedSection)
        ]);
    }

    var vm = new viewModel();
    ko.applyBindings(vm);

    var load = function (no) {
        var url = '/Home/Hello?no=' + no;
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            cache: true,
            success: function (data) {
                vm.sections()[no].items(data);
                vm.selectedSection(vm.sections()[no]);
            }
        });
    }

    $(function () {
        $("#tabs").find('a[data-toggle="tab"]').on('shown.bs.tab', function (ev) {
            var no = $(ev.target).data('no');
            load(no);
        });

        load(0);
    });
}())

 

[環境]
jQuery JavaScript Library v2.1.4
Bootstrap v3.3.6
Knockout JavaScript library v3.4.0

[参考]

Keep track of tabs with knockoutjs + twitter bootstrap

Comments are closed.

Post Navigation