简体   繁体   中英

Collapsable panel with bootstrap and knockout

I can't make an accordion with KnockoutJS, and Bootstrap to work properly. I have defined it like so:

<div class="panel-group" id="accordion" data-bind="foreach: Advertisers()">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <span data-toggle="collapse" data-bind="html: $data, attr: { 'data-target': '#' + $data }"></span>
            </h4>
        </div>
    </div>
    <div class="panel-collapse collapse" data-parent="#accordion" data-bind="attr: { id: $data }">
        <div class="panel-body">
             ...content...

"Advertisers" is an observable array of strings, and hence $data is a string. I get one "row" for each advertiser.

All rows are initially collapsed, and clicking a row expands the content below. So far so good.

The problem is that when I click another row I would expect the previous expanded to collapse, but that's not happening. (I couldn't make a fiddle to work either, with Bootstrap and KnockoutJS...)

Edited the code.

What about a simple custom binding, which also allows you to unclutter your view a bit:

ko.bindingHandlers.bootstrapAccordion = {
  init: function(elem, value, allBindings) {
    var options = ko.utils.unwrapObservable(value()),
        handleClass = '[data-toggle]',
        contentClass = '.collapse',
        openItem = ko.utils.unwrapObservable(options.openItem) || false,
        itemClass = '.' + ko.utils.unwrapObservable(options.item) || '.accordion-group',
        items = $(elem).find(contentClass);

    // toggle: false required to hide items on load
    items.collapse({ parent: elem, toggle: false });
    if (openItem > -1) items.eq(openItem).collapse('show');

    // if the array is dynamic, the collapse should be re-initiated to work properly
    var list = allBindings.get('foreach');
    if (ko.isObservable(list)) {
      list.subscribe(function() { 
        $(elem).find(contentClass).collapse({ parent: elem, toggle: false });              
      });
    }

    $(elem).on('click', handleClass, function() {
        $(elem).find(contentClass).collapse('hide');
        $(this).closest(itemClass).find(contentClass).collapse('show');
    });
  }
};

This binding takes 2 parameters (className for container, and optionally, an item to open on load), eg: bootstrapAccordion: {item: 'panel-group', openItem: 0} , and should be set on the same element which has a foreach binding. It assumes that collapsible sections have a collapse class, and the handles to toggle them have a data-toggle attribute.

See it in action here: http://jsfiddle.net/pkvn79h8/22/

I extended Tyblitz's example above to include support for changing an icon (eg, +/-, up/down arrow) and support for moving to the next panel by applying data-open-next attribute to whatever should move to next panel on click.

ko.bindingHandlers.bootstrapAccordion = {
    init: function (elem, value, allBindings) {
        var options = ko.utils.unwrapObservable(value()),
            handleClass = '[data-toggle]',
            contentClass = '.collapse',
            openedClass = ko.utils.unwrapObservable(options.openedClass) || 'fa-minus',
            closedClass = ko.utils.unwrapObservable(options.closedClass) || 'fa-plus',
            openCloseToggleClasses = openedClass + ' ' + closedClass,
            openItem = ko.utils.unwrapObservable(options.openItem) || false,
            itemClass = '.' + (ko.utils.unwrapObservable(options.item) || 'accordion-group'),
            items = $(elem).find(contentClass);

        var initializeItems = function(items) {
            // toggle: false required to hide items on load
            items.collapse({ parent: elem, toggle: false });
            if (openItem > -1) {
                items.eq(openItem).collapse('show');
                items.eq(openItem).closest(itemClass).find('.panel-heading').find('i').toggleClass(openCloseToggleClasses);
                items.eq(openItem).closest(itemClass).find('.panel-heading').addClass('active');
            }
        }

        initializeItems(items);

        // if the array is dynamic, the collapse should be re-initiated to work properly
        var list = allBindings.get('foreach');
        if (ko.isObservable(list)) {
            list.subscribe(function () {
                initializeItems($(elem).find(contentClass));
            });
        }

        $(elem).on('click', handleClass, function () {
            $(elem).find(contentClass).collapse('hide');
            $(this).closest(itemClass).find(contentClass).collapse('show');
            $(this).closest(itemClass).parent().find('.panel-heading i').removeClass(openCloseToggleClasses);
            $(this).closest(itemClass).parent().find('.panel-heading i').addClass(closedClass);
            $(this).closest(itemClass).parent().find('.panel-heading').removeClass('active');
            if ($(this).closest(itemClass).find('.panel-collapse').attr('aria-expanded') === "true") {
                $(this).closest(itemClass).find('.panel-heading i').toggleClass(openCloseToggleClasses);
                $(this).closest(itemClass).find('.panel-heading').addClass('active');
            }
        });

        $(elem).on('click', '[data-open-next]', function () {
            $next = $(this).closest(itemClass).next(itemClass).find(handleClass);
            if ($next.length) {
                $next.click();
            } else {
                $same = $(this).closest(itemClass).find(contentClass);
                $same.collapse('hide');
                $same.parent().find('.panel-heading i').removeClass(openCloseToggleClasses);
                $same.parent().find('.panel-heading i').addClass(closedClass);
                $same.parent().find('.panel-heading').removeClass('active');
            }
        });
    }
};

Sample markup to use with this binding:

<div data-bind="foreach: listOfThings, bootstrapAccordion: { openItem: 0 }">
    <div class="accordion-group">
        <div class="panel panel-default" style="cursor: pointer;" data-toggle>
            <div class="panel-heading">
                <i class="fa fa-plus fa-pull-left fa-2x"></i>
                <h3 data-bind="text: name">Title of expander</h3>
            </div>
        </div>
        <div class="panel-collapse collapse">
            <div class="panel-body">
                <div class="clearfix" data-accordion-content>
                <!-- content goes here -->

                <!-- ko if: $index() < $parent.listOfThings().length -1 -->
                <button data-open-next>Next Thing</button>
                <!-- /ko -->
                </div>
            </div>
        </div>
    </div>
</div>

I would feel bad not contributing back :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM