Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs - select change event doesn't fire the first time

Tags:

knockout.js

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

My html is 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 it so that if the property myfield has a value different to '' the change function will execute.

If I choose an element the myfunction is call and all it´s ok, but when the page is load, and for example myfield has the value "1" the function is not call, and I need that this function will be execute, I hope that you can undertand my problem.

like image 758
Julito Avellaneda Avatar asked Sep 19 '14 15:09

Julito Avellaneda


1 Answers

You're having trouble because you're fighting Knockout, not using it here :-). You should read through the selectedOptions documentation and options binding, or perhaps even do some of the KO tutorials.

Basically, you never want to handle the change event for DOM elements yourself. Knockout is meant to do exactly that: update your ViewModel when the DOM inputs change. In addition, Knockout should also be in charge of generating the options 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, e.g. 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 actually need to subscribe to a change in the dropdown, subscribe to the myfield changes instead as shown above.

like image 192
Jeroen Avatar answered Nov 12 '22 10:11

Jeroen