2012-06-18 59 views
0

我創建了一個函數,它返回我的html頁面中的所有obserables項目。這個功能的〔實施例是動態內容與淘汰

<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer" class="InputText"/> 
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer2" class="InputText"/> 
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer3" class="InputText"/> 
<input type="text" id="frmIn1-Officer" data-bind="value: AOfficer4" class="InputText"/> 

功能將reutrn [「AOfficer」,「AOfficer2」,「AOfficer3」,「AOfficer4」]

,現在我想成爲使數據的上述名單-bind elemnts obserable

viewModel = { 
AOfficer : ko.observable(), 
AOfficer2 : ko.observable(), 
AOfficer3 : ko.observable(), 
AOfficer4 : ko.observable(), 
} 
ko.applyBindings(viewModel); 

上面是這樣做的非動態的方式..但我只是不能似乎找到了解決這個問題的一個動態的方式..

我如何去解決這個?有解決方案嗎?解決辦法?

謝謝你們

回答

2

一個選項是創建一個自定義綁定,它將從現有值爲您填充視圖模型。

喜歡的東西:

ko.bindingHandlers.valueWithInit = { 
    init: function(element, valueAccessor, allBindingsAccessor, data) { 
     var property = valueAccessor(), 
      value = element.value; 

     //create the observable, if it doesn't exist 
     if (!ko.isWriteableObservable(data[property])) { 
      data[property] = ko.observable(); 
     } 
     data[property](value); 

     ko.applyBindingsToNode(element, { value: data[property] }); 

    } 
}; 

當您添加綁定,你需要指定屬性的字符串名字,這樣當它不存在最初的結合不會失敗。

如果該方法不存在或僅使用該元素的值填充現有的observable,該方法將爲您創建一個observable。

樣品在這裏:http://jsfiddle.net/rniemeyer/BnDh6/

0

也許你可以試着讓它的observableArray():

var Officers = ko.observableArray([{name: AOfficer1, o_value: xxx},{name: AOfficer2, o_value: yyy}, and so on]); 

而且你的HTML的說:我在過去使用

<ul data-bind="foreach: Officers"> 
<li><span data-bind="text: name"></span><input type="text" data-bind="value: o_value" class="InputText"/></li> 
</ul>