Question

I am trying to populate "Select" using knockout data-bind option for a list of values and set one of the values as "selected" by default.

There are two server requests,

  1. Get the list of values (dataRepository.GetLifelines)
  2. Set one of the values as Selected from the list. (dataRepository.GetMockSelectedLifeline)

First requirement has been addressed. data-bind to a select is working fine with "Selected" value.

I am having issue with setting the default "Selected Value" in the list. Can someone please help me. method is this.selectValue. It is trying to set the selectedLifeline to the matching "Name".

    function LifelineViewModel() {
    this.lifelines = ko.observableArray([{}]);
    this.selectedLifeline = ko.observable();

    this.updateData = function (data) {
        var boundUpdate = bind(function (value) {
            this.lifelines.push(value);
        }, this);

        $.each(data, function (index, item) {
            boundUpdate(item);
        });
        dataRepository.GetMockSelectedLifeline(bind(this.selectValue, this));
    }

    this.selectValue = function (data) {
        this.selectedLifeline = ko.utils.arrayFirst(this.lifelines, function (lifeline) {
            return lifeline.Name === data.Name;
        });
    }
}

LifelineViewModel.prototype.Init = function () {
    var boundUpdateData = bind(this.updateData, this);
    dataRepository.GetLifelines(boundUpdateData);
}

var bind = function (func, thisValue) {
    return function () {
        return func.apply(thisValue, arguments);
    }
}
Was it helpful?

Solution

As selectedLifeline is an observable you are not setting its value correctly.

Could you try this. Instead of:

this.selectValue = function (data) { 
    this.selectedLifeline = ko.utils.arrayFirst(this.lifelines, function (lifeline) { 
        return lifeline.Name === data.Name; 
    }); 
} 

.. something like...

this.selectValue = function (data) { 
    this.selectedLifeline(ko.utils.arrayFirst(this.lifelines, function (lifeline) { 
        return lifeline.Name === data.Name; 
    })); 
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top