0

我正在扩展视图模型。我需要实现该addEmployee方法,以便它正确引用 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"}]}
     ]
}

JavaScript:

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

document.getElementById("test").innerText = JSON.stringify(jsonModel);

var options = {
    extend: {
        "{root}": function () {

            var self = this;
            var employees = new Array();

            self.employees = ko.observableArray(employees);
            var arrayTest = [{ "FirstName": "test", "LastName": "test", "Addresses": [{ "StreetNumber": "MI6", "StreetName": "Undisclosed" }, { "StreetNumber": "SAS", "StreetName": "Undisclosed" }] }];

            self.addEmployee = function () {
                self.employees.push(arrayTest);

            }.bind(self);
        }
    }
}

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

});

我将不胜感激任何帮助。谢谢!

4

2 回答 2

0

尝试这个:

var kovmmappingVM = ko.viewmodel.fromModel(jsonModel, options);
kovmmappingVM.addEmployee = function (empl) {
    kovmmappingVM.Employees.push(empl);
}
ko.applyBindings(kovmmappingVM, document.getElementById("POC"));
于 2014-06-03T13:12:43.497 回答
0

这有效:

var Employee = function () {

var self = this;    
self.addEmployee = function (kovmmappingVM) {

    kovmmappingVM.Employees.push({
                                    FirstName: "test",
                                    LastName: "test",
                                    Addresses: [{ "StreetNumber": "MI6", "StreetName":   "Undisclosed" }, { "StreetNumber": "SAS", "StreetName": "Undisclosed" }]

                                 });

    model = ko.viewmodel.toModel(kovmmappingVM);
    document.getElementById("test2").innerText = JSON.stringify(model);

    }.bind(self);
}


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

    document.getElementById("test").innerText = JSON.stringify(jsonModel);

    var options = {
        extend: {
            "{root}": Employee
        }
    };

    var kovmmappingVM = ko.viewmodel.fromModel(jsonModel, options);   

    ko.applyBindings(kovmmappingVM, document.getElementById("POC"));  
});
于 2014-06-03T14:46:11.883 回答