使用knockout viewmodel插件时如何扩展knockout viewmodel?

时间:2014-06-02 13:20:45

标签: json knockout.js formatting knockout-viewmodel-plugin

我正在使用 knockout.viewmodel 插件(http://coderenaissance.github.io/knockout.viewmodel/)动态生成 viewModels ,返回 JSON 通过 WebAPI
我遇到了扩展 viewModel 的问题 以下是我的测试脚本示例:

JSON:

{"Employees":
    [
     {"FirstName":"James",
      "LastName":"Bond",
      "Addresses":[{"StreetNumber":"MI6","StreetName":"Undisclosed"},
                   {"StreetNumber":"SAS","StreetName":"Undisclosed"}]},
     {"FirstName":"Jason",
      "LastName":"Bourne",
      "Addresses":[{"StreetNumber":"CIA","StreetName":"Undisclosed"},
                   {"StreetNumber":"NSA","StreetName":"Undisclosed"}]}
    ]
}

标记:

<div id="POC">
    <div id="test"></div>
    <table>           
        <tbody data-bind="foreach: Employees">
            <tr>
                <td data-bind="text: FirstName"></td>
                <td data-bind="text: LastName"></td>
            </tr>
            <tr>
                <td colspan="2">
                    <table style="color:blue">                            
                        <tbody data-bind="foreach: Addresses">
                            <tr>
                                <td data-bind="text: StreetNumber"></td>
                                <td data-bind="text: StreetName"></td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>

    <table>
        <tr>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>First Name</td>
            <td><input width="150" /></td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td><input width="150" data-bind="" /></td>
        </tr>
        <tr>
            <td></td>
            <td><button data-bind="click: addEmployee ">Add Agent</button></td>
        </tr>
    </table>
</div>

JavaScript的:

$.getJSON("http://localhost:58191/api/employees", function (jsonModel) {

var options = {
    extend: {
        "{root}.Employees[i]": function (employee) {
            employee.addEmployee = function () {
                alert("add");
            }
        }
    }
}

var kovmmappingVM = ko.viewmodel.fromModel(jsonModel, options);    
ko.applyBindings(kovmmappingVM, document.getElementById("POC"));
});

JSON 已正确处理和绑定,但扩展功能未接通。
我没有任何例外;警报只是不起火。
任何见解将不胜感激。

1 个答案:

答案 0 :(得分:0)

您在{root}.Employees[i]而不是{root}.Employees上宣布了您的扩展程序。因此,该函数被添加到每个Employees,但您的标记绑定到根,因为它在foreach之外。

替换为:

var options = {
    extend: {
        "{root}.Employees": function (employees) {
            employees.addEmployee = function () {
                alert("add");
            }
        }
    }
}

OR

将您的按钮放在foreach