Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two select lists sharing same value binding, slow to update

Tags:

knockout.js

I have two select lists bound to observable arrays containing a different sorting of the same data. Both of these select list value binding is to the same observableArray.

HTML

  <select id="countriesAZ" data-bind="value: selectedCountry, options: countriesAZ, optionsText: 'Name', optionsValue: 'Id',  optionsCaption: 'Countries a - z'"></select>

  <select id="countriesByDistance" data-bind="value: selectedCountry, options: countriesDist, optionsText: 'Name', optionsValue: 'Id',  optionsCaption: 'Countries by distance'"></select>

JS

var myVM = function() {
    var self = this;
    this.countriesAZ = ko.observableArray([{"Id":1,"Name":"Scotland"},{"Id":2,"Name":"England"},{"Id":3,"Name":"Wales"},{"Id":4,"Name":"N. Ireland"}]);
    this.countriesDist = ko.observableArray([{"Id":1,"Name":"Scotland"},{"Id":2,"Name":"England"},{"Id":3,"Name":"Wales"},{"Id":4,"Name":"N. Ireland"}]);
    this.selectedCountry = ko.observableArray();
}

window.viewModel = new myVM();
ko.applyBindings(viewModel);

In this fiddle it all seems to work well and react quickly, however, the actual array has around 1000 items and there is a delay when changing one of the selects.

I have tried to put a throttle on the value binding but didn't seem to make a difference.

like image 649
PMC Avatar asked Aug 08 '26 19:08

PMC


1 Answers

You will run into performance problems when using large numbers of options generated by the options binding while also using the value binding. This problem is described quite well in this blog post by Ryan Niemeyer. He also explains a number of ways to work around this problem.

The simplest fix, though, might be to use my Freedom plugin that fixes the underlying Knockout bug. Here's your example with the Freedom plugin included: http://jsfiddle.net/mbest/sHatN/3/

like image 141
Michael Best Avatar answered Aug 12 '26 10:08

Michael Best



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!