簡體   English   中英

剔除可觀察數組設置選定值

[英]knockout observable array set selected value

我試圖使用敲除數據綁定選項填充“選擇”作為值列表,並默認將其中一個值設置為“選定”。

有兩個服務器請求,

  1. 獲取值列表(dataRepository.GetLifelines)
  2. 從列表中將值之一設置為“已選擇”。 (dataRepository.GetMockSelectedLifeline)

第一個要求已得到解決。 將數據綁定到選擇項時,使用“ Selected”值可以正常工作。

我在列表中設置默認的“選定值”時遇到問題 有人可以幫幫我嗎。 方法是this.selectValue 它試圖將selectedLifeline設置為匹配的“名稱”。

    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);
    }
}

由於selectedLifeline是可觀察的,因此您沒有正確設置其值。

你可以試試這個嗎? 代替:

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

.. 就像是...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM