我使用了淘汰赛这样的对象
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();
};
并且viewmodel看起来像这样
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/
答案 0 :(得分:1)
您正在初始化Employee
个实例:self
未定义,您需要this
。此外,alert(item.Name)
将显示一个函数,因为item.Name
也是一个可观察的(您只展开self.newEmployee
可观察对象,但其属性仍然是可观察的。)