Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom binding for multiple selection in knockout js

Tags:

knockout.js

I'm trying to create custom binding in knockout to use it as multiple selection field. For example: I want to design selection screen for invoice report. On this selection screen I would like to use field 'Invoice Type' to allow users to provide only the types of invoices, they are interested in. If I use standard text box for this field, users would be allowed only to provide one invoice type. I want them to be able to provide more than one type in selection. My idea was to prepare a binding such as:

// html
<input data-bind="multiple: { data: optionsArray }" />
...
// view  model
optionsArray = ko.observableArray();

where I could provide field 'optionsArray', which would hold the multiple choise of users (in my case that would be multiple invoice types). If it comes to UI, I thought it could look like this: there's a button next to the element with multiple binding. After clicking it, dialog window appears and all the 'optionsArray' elements are displayed there and can be changed, new can be added or deleted.

I don't know how to achieve this because I failed on the part of displaying all the optionsArray elements in dialog box in a way they can be edited as observables and all the changes are reflected in viewModel.optionsArray. Is this even possible?

Do you have any experience in building custom bindings and help me with this?

like image 996
Eori Avatar asked Oct 25 '12 12:10

Eori


1 Answers

You don't need to create custom binding for that. You can use selectedOptions binding here is link to the documentation: http://knockoutjs.com/documentation/selectedOptions-binding.html.

Add optionsArray and selectedTypes observable arrays to your view model:

self.optionsArray = ko.observableArray();
self.selectedTypes = ko.observableArray();

And bind to multiselect:

<select data-bind="options: optionsArray, selectedOptions: selectedTypes" size="5" multiple="true"></select>

Here is working example with dialog and adding new options: http://jsfiddle.net/vyshniakov/nZtZd/

like image 140
Artem Vyshniakov Avatar answered Nov 02 '22 05:11

Artem Vyshniakov