在foreach中的observableArray中选择knockout.js自定义内容

时间:2013-02-26 04:50:07

标签: knockout.js

我有以下html片段:

<tbody data-bind="foreach: ptData">
            <tr id="Tr1">
                <td><a data-bind="attr: {href: '/ProjectTrack/IssueGrid.aspx?IssueID='+ptId}">PT Launch</a></td>
                <td nowrap="nowrap" data-bind="text: ptId">
                </td>
                <td nowrap="nowrap" data-bind="text: ptProject">
                </td>
                <td nowrap="nowrap" data-bind="text: ptTitle">
                </td>
                <td nowrap="nowrap" data-bind="text: ptPriority">
                </td>
                <td nowrap="nowrap" data-bind="text: ptType">
                </td>
                <td nowrap="nowrap" data-bind="text: ptStatus">
                </td>
                <td nowrap="nowrap" data-bind="text: ptUpdated">
                </td>
                <td nowrap="nowrap" data-bind="text: ptAssignedTo">
                </td>
                <td style="display: none" data-bind="text: ptUrl">
                </td>
            </tr>
        </tbody>

我有以下viewModel,其中包含动态内容:

var viewModel = {
        ptData: ko.observableArray([])
    };



function DataResult(ptId, ptProject, ptTitle, ptPriority, ptType, ptStatus, ptUpdated, ptAssignedTo, ptDesc, ptUrl) {
        this.ptId = ko.observable(ptId);
        this.ptProject = ko.observable(ptProject);
        this.ptTitle = ko.observable(ptTitle);
        this.ptPriority = ko.observable(ptPriority);
        this.ptType = ko.observable(ptType);
        this.ptStatus = ko.observable(ptStatus);
        this.ptUpdated = ko.observable(ptUpdated);
        this.ptAssignedTo = ko.observable(ptAssignedTo);
        this.ptDesc = ko.observable(ptDesc);
        this.ptUrl = ko.observable(ptUrl);
    }

我有一个jQuery ajax调用来返回填充在DataResult对象中的数据,并且每个DataResult对象都被推送到viewModel.ptData。以下knockout.js命令似乎在HTML代码段中不起作用:

"attr: {href: '/ProjectTrack/IssueGrid.aspx?IssueID='+ptId".  

我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

如果要绑定到一个表达式(这里是构建带有+的链接),你有可观察的属性(ptId),你必须像函数一样调用它们。所以你错过了()

<a data-bind="attr: {href: '/ProjectTrack/IssueGrid.aspx?IssueID=' + ptId() }">

但是,如果您要创建一个计算的obseravable来生成链接:

function DataResult(ptId, ....) {        
        this.ptId = ko.observable(ptId);
        this.launchLink = ko.computed(function(){
            return '/ProjectTrack/IssueGrid.aspx?IssueID=' + this.ptId()
        }, this);
}

然后你在绑定中不需要(),因为现在你直接绑定到一个observable:

<a data-bind="attr: { href: launchLink }">