简体   繁体   中英

Knockout writable computed observables

I'm currently building a very number-heavy application using Knockout and I've ran into a problem with making a computed observable writable.

Currently I have a dropdown option where the user selects an age group and the selected value from this populates the text input next to it to show the population for that age group which is a computed observable. Both the dropdown and the text input values are populated from an array.

I have set up a codepen below but basically you'll see that the text input's value is generated via a computed observable and the correct formatting (via a custom binding handler!) is applied when you select a value from the dropdown.

The problem I'm having is that if you enter a custom value into the text input (inputted straight into the textbox as opposed to selecting a value from the dropdown) then when you blur out of the textbox, the custom formatting isn't applied to the value that you input and I'm pretty unsure how to go about tackling this problem.

self.selectedPopulation = ko.computed({

    read: function () {
      return self.chosenAge().population;
    },

    write: function (value) {
      // write value back here?
    },

  });

Codepen: http://codepen.io/anon/pen/HkguL (write function is at Line 76.)

You've need to make the selectedPopulation a normal observable, and subscribe to the chosenAge observable to be notified when it changed.

You'll need to create chosenAge with a dummy object to stop knockout blowing up on binding:

self.chosenAge = ko.observable({age: '', population: ''});

And then change your computed to an observable:

// Selected population
self.selectedPopulation = ko.observable('');

And subscribe to the chosenAge observable:

self.chosenAge.subscribe(function (newValue) {
    self.selectedPopulation(newValue.population);
});

I've not used CodePen before, but I've updated your code here in case I've missed anything in my working example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM