2011-10-23 3 views
0

다음과 같이 viewmodel과 연관된 템플리트가 있습니다.녹아웃 : HTML 템플리트에서 viewmodel 인스턴스에 액세스합니다.

var AilmentItem = function() { 
    this.SelectedAilment = ko.observable(); 
} 

function AilmentsViewModel() { 
    this.Ailments = ko.observableArray([new AilmentItem()]); 
    this.AilmentsType = ko.observableArray([{ Name: 'Diabetes' }, { Name: 'Arthritis' }, { Name: 'High BP'}]); 
} 

드롭 다운 나는이 열 중 하나에 AilmentsType를 결합하는 데 필요한 HTML 템플릿에서 HTML 스크립트

<script type="text/javascript"> 
    $(function() { 
     var AilmentsVM = new AilmentsViewModel(); 
     ko.applyBindings(AilmentsVM, $('#Ailments')[0]); 
    }); 
</script> 
<div id="Ailments"> 
    <div> 
     <table> 
      <tbody data-bind='template: { name: "ailmentRowTemplate", foreach: Ailments }'> 
      </tbody> 
     </table> 
    </div> 
</div> 
<script type="text/html" id="ailmentRowTemplate"> 
    <tr> 
     <td><select data-bind="options: AilmentsVM.AilmentsType(), optionsText: 'Name', value: SelectedAilment"></select></td> 
    </tr> 
</script> 

. 누군가 그것을 달성하는 방법을 안내 할 수 있습니까? 감사.

답변

1

귀하의 AilmentsVM은 jQuery 준비 블록에서 작성되므로 전역 범위가 없으므로 데이터 바인딩에서 직접 액세스 할 수 없습니다.

1.3 베타 버전을 사용하는 경우 Knockout에서 제공하는 $root 또는 $parent 특수 변수를 사용할 수 있습니다. 이 경우 최상위 범위의 한 수준에 불과하기 때문에 동일합니다. 그럼, 그냥 : $root.AilmentsType.

이전 버전을 사용하는 경우 templateOptions 기능을 사용하여 jQuery 템플릿에 옵션을 전달할 수 있습니다. 그 결과는 다음과 같습니다

<tbody data-bind='template: { name: "ailmentRowTemplate", foreach: Ailments, templateOptions: { types: AilmentsType } }'> 
</tbody> 

그런 다음 액세스가 좋아 :

<select data-bind="options: $item.types, optionsText: 'Name', value: SelectedAilment"></select> 
+0

감사 RP 메이어를. 나는 1.3으로 전환했고 그것은 단순화하고있다. –