Knockoutjs - change event selection does not work for the first time

I have a problem with a single select element. I create a binding for the change event, and it works when I change the selected item manually, but if the select element is a binding to the specified value, the change function is not a call.

My html looks like this:

 <select data-bind="value: myfield, event:{change:myfunction}"> <option value="">Select an element</option> <option value="1">Element 1</option> <option value="2">Element 2</option> </select> 

I need this, so if the myfield property has a value other than ``, the change function will be executed.

If I select an element, then myfunction is a call, and everything is fine, but when the page loads and, for example, myfield has a value of "1", the function is not a call, and I need this function to be executed, I hope that you can solve my problem.

+5
source share
1 answer

You have problems because you are fighting a knockout, and not using it here :-). You should read the documentation for selectedOptions and options binding, or maybe even follow some of the KO tutorials .

Basically, you never want to handle the change event for DOM elements yourself. The knockout is just for that: update the ViewModel when the DOM inputs change. In addition, Knockout should also be responsible for creating the option for you.

Your html should look something like this:

 var ViewModel = function() { var self = this; self.availableOptions = [1, 2]; self.myfield = ko.observable(); self.myfield.subscribe(function(newValue) { // Handle a change here, eg update something on the server with Ajax. alert('myfield changed to ' + newValue); }); } ko.applyBindings(new ViewModel()); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <select data-bind="options: availableOptions, value: myfield, optionsCaption: 'Select an element'"> </select> 

If you really need to subscribe to the drop-down list change, subscribe to myfield changes as shown above.

+21
source

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


All Articles