2013-02-14 70 views
1

我想獲取可觀察數組中的值並將其顯示在下拉列表中,但我不想將下拉列表中的值更新爲可觀察數組更改?由於其他原因,該陣列必須是可觀察的。從可觀察數組中敲除+填充值,但在數組更新時不更新值

我知道會有一個簡單的方法來做到這一點!

這裏是一個fiddle來解釋我的意思和代碼如下。

視圖模型:

ViewModel = function() { 
    var self = this; 
    self.Owners = ko.observableArray([ 
     {FullName: 'Bob Jones',Id: 1}, 
     {FullName: 'Joe Bloggs',Id: 2}, 
     {FullName: 'Joe Bloggs',Id: 2} 
    ]); 

    self.GetOwners = function() { 
     var ownerIds = [], 
      addedIds = [], 
      count = 0; 

     var owners = ko.utils.arrayForEach(self.Owners(), function (owner) { 
      if (addedIds.indexOf(owner.Id) == -1) { 
       addedIds[count] = owner.Id; 
       ownerIds[count] = { 
        FullName: owner.FullName, 
        Id: owner.Id 
       }; 

       count++; 
      } 
     }); 

     return ownerIds; 
    } 

    self.Add = function() { 
     self.Owners.push({ FullName: 'Jane Doe', Id: 3 }); 
    } 
}; 

var vm = new ViewModel(); 
ko.applyBindings(vm); 

HTML:

<select data-bind="options: GetOwners(), optionsText: 'FullName', optionsValue: 'Id'"> </select> 
<!-- I dont want the values in this select to update when I add an owner by clicking the button below --> 

<button data-bind="click: Add">Add</button> 

回答

4

這聽起來像你應該只使用第二observableArray在下拉列表中的值。這樣,原始觀察者可以改變而不受影響。

+1

好主意,太簡單了!感謝那。 – Colin 2013-02-17 08:49:59