【问题标题】:dynamic data binding in nested templates in knockout js淘汰赛js中嵌套模板中的动态数据绑定
【发布时间】:2012-11-06 05:07:35
【问题描述】:

我正在使用 MVC 框架和淘汰赛 js 组合。我对淘汰赛js有点陌生。我需要通过嵌套剔除模板中的 API 调用动态绑定数据。我没有找到任何方法来做到这一点。

我的嵌套模板是:

enter code here
<div data-bind="template: {name: 'ListTemplate', foreach: Data}">
</div>

<script type="text/html" id="ListTemplate">
    <h3>
        Contributions (${ Count })
    </h3>
    <img src=" ${ Image } " />
    <p>
       <span> ${ Name } </span>
       <div data-bind="template: {name: 'goalsTemplate', foreach: goals}"></div>
    </p>
</script>

<script type="text/html" id="goalsTemplate">
    Goal:
    <a href="#"> ${ Goals } </a> Ends on
    <code> ${ Date } </code>
</script>

我的 viewModel 是:

var viewModel = {(
    Data: ko.observableArray([]),
    goals: ko.observableArray([])
});

function userData(Count, Image, Name) {
        return {
            Count: ko.observable(Count),
            Image: ko.observable(Image),
            Name: ko.observable(Name)
        };
}

function goalDetail(Goals, Date) {
        return {
            Goals: ko.observable(Goals),
            Date: ko.observable(Date)
        };
}

$(document).ready(function() {
     $.ajax({
            type: "GET",
            url: siteBaseUrl + 'api/Detail',
            dataType: 'json',
            success: function (data) {
                $(data).each(function (index, type) {
                    viewModel.Data.push(new userData(..,..,..));
                });
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('error status code:' + xhr.status);
                alert('error message:' + thrownError);
                alert('error details:' + xhr.responseText);
            }
        });
});

如何通过Data数组内部的function(goalDetail)绑定目标数组中的数据?

【问题讨论】:

    标签: javascript jquery-plugins knockout.js knockout-templating


    【解决方案1】:

    据我了解,目标和数据是主视图模型的一部分,您想在 Foreach 绑定中使用父视图模型,在这种情况下,您只需要 $parent 如下所示

    <div data-bind="template: {name: 'goalsTemplate', foreach: $parent.goals}">
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 2013-05-31
    • 1970-01-01
    • 2013-08-14
    • 1970-01-01
    • 2013-04-17
    相关资源
    最近更新 更多