Knockout-jQueryUI

Fork me on GitHub

Accordion.html

Convert a pair of headers and content panels into an accordion.

Parameters

For each of the widget's options the binding has a corresponding option with the same name. These can be set to static values, or bound either to normal or to observable properties of the viewmodel.

For each of the widget's events the binding has a corresponding option with the same name. These can be set to functions. When invoked the value of the this keyword evaluates to the viewmodel.

refreshOn

Should be bound to one of the viewmodel's observables. Every time that observable changes, the widget is refreshed (it's refresh method is invoked).

widget

Should be bound to one of the viewmodel's writeable observables. The binding will write a jQuery object containing the binding's DOM element into it. The primary use for this option is to invoke the widget's methods on the element.

active [two-way binding]

Which panel is currently open.

Example

HTML

<select data-bind="value: selected">
  <option value="0">Panel 1</option>
  <option value="1">Panel 2</option>
  <option value="2">Panel 3</option>
</select>
<div data-bind="accordion: { active: active }">
  <h3>Panel 1</h3>
  <div>Lorem ipsum dolor sit amet</div>
  <h3>Panel 2</h3>
  <div>consectetur adipiscing elit</div>
  <h3>Panel 3</h3>
  <div>Nunc tincidunt consectetur sagittis</div>
</div>

JavaScript

var ViewModel = function () {
  this.active = ko.observable(0);
  this.selected = ko.computed({
      read: function() { return this.active().toString(); },
      write: function(newValue) { this.active(parseInt(newValue, 10)); },
      owner: this
  });
};

Result

Panel 1

Lorem ipsum dolor sit amet

Panel 2

consectetur adipiscing elit

Panel 3

Nunc tincidunt consectetur sagittis