0

I'm using the knockout.viewmodel plugin (http://coderenaissance.github.io/knockout.viewmodel/) to generate my viewModels on the fly from JSON returned via WebAPI.
I'm having an issue extending the viewModel though.
Here's a sample of my test script:

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"}]}
    ]
}

Markup:

<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"));
});

The JSON is processed and bound properly, but the extended function doesn't get wired up.
I don't get any exceptions; the alert just doesn't fire.
Any insight would be greatly appreciated.

4

1 回答 1

0

您声明了您的扩展名{root}.Employees[i]而不是{root}.Employees. 因此,该函数被添加到每个Employees,但您的标记绑定到根,因为它在foreach.

替换为:

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

或者

把你的按钮放在里面foreach

于 2014-06-02T13:26:07.897 回答