0

我用这样的物体进行淘汰赛

            var Employee = function () {
                self.Name = ko.observable();
                self.Id = ko.observable();
                self.Manager = ko.observable();
                self.Title = ko.observable();
                self.Salary = ko.observable();
                self.Age = ko.observable();
            };

并且视图模型看起来像这样

            var EmployeesViewModel = function () {
                var self = this;
                var url = "/api/employees";
                var refresh = function() {
                    $.getJSON(url, { }, function(data) { self.Employees(data); });
                };

                // Public data properties
                self.Employees = ko.observableArray([]);
                self.newEmployee = ko.observable(new Employee());

                // Public operations
                self.addEmployee = function (model, event) {
                    var item = self.newEmployee();
                    alert(model); // always undefined
                    self.Employees.push(item);
                };
                self.removeEmployee = function (employee) {
                    self.Employees.remove(employee);
                    removeEmployee(employee);
                };
                refresh();
            };
            ko.applyBindings(new EmployeesViewModel());

self.addEmployee方法中,当我使用该项目时,我得到空值,尽管该项目已添加到列表中并显示在网格中。

编辑:jsfiddle http://jsfiddle.net/magedfarag/b4tsX/中的问题

4

1 回答 1

1

您正在Employee错误地初始化您的实例:self在那里未定义,您需要this. 此外,alert(item.Name)将显示一个函数,因为item.Name它也是一个可观察对象(您只展开self.newEmployee可观察对象,但其属性仍然是可观察对象)。

更新了小提琴

于 2012-10-05T09:58:10.243 回答