2012-06-18 2 views
0

Ive는 HTML 페이지의 모든 관측 항목을 반환하는 함수를 만들었습니다. 이 함수의 exmaple는넉 아웃으로 관찰되는 동적 컨텐츠

<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"/> 
함수는 [ 'AOfficer', 'AOfficer2', 'AOfficer3', 'AOfficer4를'] reutrn 것이다

이다

지금은 될 데이터의 상기 목록을 만들고 싶어 -bind 내가이 문제를 해결하는 갈 것이라고 어떻게 ..

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

위 obserable elemnts이 일의 유엔 - 동적 인 방법은 ...입니다하지만 난 그냥 질수는이 문제를 해결하기 위해 동적 인 방법을 찾을 수가 ? 해결책이 있습니까? 주위에 작품?

고마워

어쩌면

답변

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

    } 
}; 

, 당신이 처음에 존재하지 않는 경우 바인딩이 실패하지 않도록, 문자열로 속성 이름을 지정해야합니다 같은

뭔가.

이 방법은 존재하지 않는 경우 관찰자를 만들거나 기존 관측 대상에 요소 값을 채 웁니다.

샘플 : 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>