Knockout Example

Selection Boxes can be used along with Knockout JS. Conceptually, a Selection Box is a kind of 'view' of the underlying html select box. When the latter changes, the former listens for these changes and updates itself accordingly. Knockout and other Javascript libraries never have to know anything about Selection Box, only interacting with the native html element itself.

In this example, we create an observableArray which contains the four 'home' nations. In addition, we have the observable 'country' which will hold the currently selected value.

var vm = {
	countries : ko.observableArray([
		'Scotland', 'England', 'Ireland', 'Wales'
	]),
	country : ko.observable()
};
ko.applyBindings(vm);

Knockout takes this observableArray and uses it to populate this select box. Subsequently, our code will take this element and generate a Selection Box component from it.

By default, the native element is hidden, but we have configured it to remain visible so that you can gain an understanding as to how it works. If you play around with it, you will see that updating one results in the other updating also.

The area below contains an element bound to current selected value. You should see it remaining in sync with the generated component

Responding to changes in the observableArray

When an observableArray is bound to a select drop down, changes to the underlying array propagate through into the dropdown. SelectionBoxes support this functionality. When you select a country from the dropdown below, the selected country is pushed into the backing array for our component. If you open up SelectionBox dropdown, you will see that the new country has been added.