简体   繁体   English

淘汰赛:在HTML模板中访问ViewModel实例

[英]Knockout: accessing viewmodel instance in HTML template

I am having a viewmodel and an associated template as below. 我有一个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'}]);
}

HTML script 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>

In the HTML template I need to bind AilmentsType to one of the columns as drop down. 在HTML模板中,我需要将AilmentsType绑定到下拉列表中的一列。 Can someone guide me how to achieve it? 有人可以指导我如何实现它吗? Thanks. 谢谢。

Your AilmentsVM does not have global scope, because it is being created in your jQuery ready block, so you can't access it directly in a data-bind. 您的AilmentsVM没有全局作用域,因为它是在jQuery ready块中创建的,因此您不能直接在数据绑定中访问它。

If you are using 1.3 beta, then you can use either the $root or $parent special variables that Knockout provides. 如果您使用的是1.3 Beta,则可以使用Knockout提供的$root$parent特殊变量。 In this case, they would be the same, as you are only one level in from the top-level scope. 在这种情况下,它们将是相同的,因为您离顶级范围仅一个级别。 So, just do: $root.AilmentsType . 因此,只需执行: $root.AilmentsType

If you are using an earlier version, then you can use the templateOptions functionality to pass options to a jQuery template. 如果使用的是较早版本,则可以使用templateOptions功能将选项传递给jQuery模板。 It would look like this: 它看起来像这样:

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

Then, access it like: 然后,像这样访问它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM