Knockout.js,foreach和afterRender

时间:2014-01-27 10:42:39

标签: jquery knockout.js

在渲染了obervable数组中的最后一个值之后,有没有办法让事件变得晦涩难懂? 我有以下代码:

<table class="resultListTable">
<thead class="header">
    <tr>
        <th>#</th>
        <th>Customer</th>
        <th>Status</th>
    </tr>
</thead>
<tbody data-bind="foreach: { data: resultList, afterRender: afterRender}">
    <tr class="resultList" data-bind="attr: {id: Rno}">
        <td data-bind="text: Id"></td>
        <td data-bind="text: Customer"></td>
        <td data-bind="text: Status"></td>
    </tr>
</tbody>
</table>

<script>

    function afterRender() {

        $(".resultList").on("click", function (e) {
            if(!exceptionRedirected){
                var url = '~/Home/Detail/' +  $(e.target).closest("tr").attr("id");
                window.location.href = url;
            }
        });
    }

function viewModel(){
    var self = this;
    self.resultList = ko.observableArray([]);
}

function CustStatus(data) {
     var self = this;   
     self.Id = ko.observable(data.Id || '');
     self.Rno = ko.observable(data.Rno || '');
     self.Customer = ko.observable(data.Id || '');
     self.Status = ko.observable(data.Id || '');
}

    var vm = new CustStatus();
    ko.applyBindings(vm);

    /* I get the data from a ajax call somewhere else in the code */

</script>

对每一行数据执行afterRender函数。 如何只在数据数组的末尾执行此操作?

1 个答案:

答案 0 :(得分:1)

您可以使用click knockout binding。

<tbody data-bind="foreach: { data: resultList}">
    <tr class="resultList" data-bind="attr: {id: Rno}, click: $root.detailClick">
        <td data-bind="text: Id"></td>
        <td data-bind="text: Customer"></td>
        <td data-bind="text: Status"></td>
    </tr>
</tbody>

使用viewModel中的detailClick函数:

function viewModel(){
    var self = this;
    self.resultList = ko.observableArray([]);

    self.detailClick = function(custStatus) {
         var url = '~/Home/Detail/' + custStatus.Rno();
         window.location.href = url;
    }
}