JS knockout and Chosen multiselect not working

I am using knockout js and the selected plugin (https://github.com/harvesthq/chosen) to try and make a multi-user choice.

I tried different ways, but I can not get multiselect to work with the data that I use. When I press the multi selector, the values ​​are not displayed, even if the parameter binding contains the correct data.

HTML:

<select multiple="multiple" data-bind="options: allCustomers, selectedOptions: event().customers, optionsText: 'name', optionsValue: 'id', chosen: true " ></select>​ 

A simplified version of the view model:

  function Event() { this.customers = ko.observableArray(); }; //for chosen plugin ko.bindingHandlers.chosen = { update: function(element, valueAccessor, allBindingsAccessor, viewModel) { $(element).chosen(); } } function ViewModel() { this.event = ko.observable(new Event()); this.allCustomers = ko.observableArray(); }; var viewModel = new ViewModel(); $.getJSON("/get_json", function(data) { for (var c = 0; c < data.customers.length; c++) { viewModel.allCustomers.push(data.customers[c]); } }); ko.applyBindings(viewModel); 

PHP:

 function get_json() { $eventData = array( 'customers' => array(array('name' => 'Bob', 'id' => 1), array('name' => 'John', 'id' => 2)), 'moreData' => array(), 'evenMoreData' => array() ); echo json_encode($eventData); } 

The selected style selection window is displayed here, but when I click on it, no options appear.

When I create a local JS array in the client view model and pass this to all clients, the multi selector works correctly (see my jsfiddle ), so this is due to receiving data from the server, but I looked at it for a while and did not see a problem!

Any help is much appreciated

+6
source share
2 answers

I found the problem after @Tyrsius suggested that it might not update the data after the initial bind.

I added $(element).trigger("liszt:updated"); to user binding, for example:

 ko.bindingHandlers.chosen = { update: function(element, valueAccessor, allBindingsAccessor, viewModel) { $(element).chosen(); $(element).trigger("liszt:updated"); } } 
+16
source

For some reason, the code in the accepted version did not work for me. Probably because the liszt:updated command does not start the one selected for updating. Based on docs here, I wrote my own version:

 ko.bindingHandlers.chosen = { init: function (element, valueAccessor, allBindingsAccessor, viewModel) { $(element).chosen({ width: "95%", placeholder_text_multiple: "Select..." }); var value = ko.unwrap(valueAccessor()); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel) { var value = ko.unwrap(valueAccessor()); $(element).trigger("chosen:updated"); } } 
+1
source

Source: https://habr.com/ru/post/919904/


All Articles