I used an object like this with knockout
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();
};
and the viewmodel look like this
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());
in self.addEmployee method when I use the item I get null value although the item is added to the list and is displayed in the grid.
edit:
the problem in jsfiddle
http://jsfiddle.net/magedfarag/b4tsX/
You are initializing your
Employeeinstances incorrectly:selfis undefined there, you needthis. Also,alert(item.Name)will display a function, asitem.Nameis also an observable (you’re unwrapping only theself.newEmployeeobservable, but its properties remain observables).Updated fiddle.