Search code examples
asp.net-mvcknockout.jsknockout-mvc

How to run a function when a value is set when using knockout


I need to get a value from the database after page load is complete and run a function that will populate several dropdowns depending on the value that has been retrieved. Like a change event for a form control.

How can I do this using Knockout.js?

Thanks.


Solution

  • Here's a quick and dirty example. The idea is to:

    1. Setup an observable array that will hold the data for your drop down. Initially, the array will be empty and your drop down will have no content.
    2. Use getJSON to retrieve data from your server.
    3. Fill your drop down list on the callback of getJSON. If I understand you correctly, you will not be retrieving the actual contents of the drop down list, but some other piece of information that will help you to decide what options will be shown. I incorporated this idea into the example.

    Btw, Countries does not have to be an array of strings. It can be an array of complex JS-objects. However, you'll have to expand your data-bind="options: ..." binding with optionsText and optionsValue to indicate what property of your object is the label and value. Look here for more details.

    var CompanyViewModel = function()
    {
        var self = this;
    
        self.Countries = ko.observableArray();
    
        $.getJSON('api/countries', function(data) {
            if(data == 1)
            {
                self.Countries(['France', 'Germany', 'Spain'])
            } else if(data == 2)
            {
                self.Countries(['Holland', 'Belgium', 'Luxemburg']);
            }
        });
     }