使用下拉列表敲除更改多个文本框

时间:2014-05-12 12:54:57

标签: javascript jquery knockout.js

我有以下HTML:

<select id="EmpName" data-bind="value: Employee.EmpName, event: { change: $root.updateEmployee }"></select>
<input disabled type="text" id="EmpNum" data-bind="value: Employee.EmpNum, valueUpdate: 'input'" />
<input disabled type="text" id="EmpClass" data-bind="value: Employee.EmpClass, valueUpdate: 'input'" />
<input disabled type="text" id="EmpDept" data-bind="value: Employee.EmpDept, valueUpdate: 'input' " />
<input disabled type="text" id="EmpStat" data-bind="value: Employee.EmpStat, valueUpdate: 'input'" />

它受以下ViewModel的约束:

generalViewModel = function (thisData) {
        var self = this;

        this.Incident = ko.mapping.fromJS(thisData.Incident);
        this.Employee = ko.mapping.fromJS(thisData.Employee);

        this.updateEmployee = function () {
            var employeeName = self.Employee.EmpName;
            $.getJSON('/Incidents/GetEmployee', { EmployeeName: employeeName }, function (data, status, xhr) {
                    var newEmp = ko.mapping.fromJS(data);
                    self.Employee(newEmp);
                });
        }

        this.refreshData = function (incID) {
            GetIncidentGeneralInfo(incID, node);
        }

        this.savetoServer = function (incID, buttonID) {
            var incident = ko.toJSON(self.Incident);
            var employee = ko.toJSON(self.Employee);
            $.post('/Incidents/SaveIncident', { IncidentID: incID, JSONIncident: incident, JSONEmployee: employee, button: buttonID }, function (data, status, xhr) {
                self.refreshData(data);
            });
        }
    }

    ko.applyBindings(new generalViewModel(data), document.getElementById(node));

除了updateEmployee函数之外,一切都运行得很好。 JSON返回新的Employee信息,但文本框没有更新。我正在做一些愚蠢的错误,我无法弄清楚wat

1 个答案:

答案 0 :(得分:1)

而不是

var newEmp = ko.mapping.fromJS(data);
self.Employee(newEmp);

你应该做

ko.mapping.fromJS(data, self.Employee);

这将更新第一次调用self.Employee时创建的ko.mapping.fromJS上的所有可观察属性。