2012-10-05 84 views
0

我使用的物體像這樣與敲除如何使用敲除可觀察到的作爲JSON對象

  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方法當我使用item儘管項目已添加到列表中並顯示在網格中,但我還是得到了空值。

編輯: 中的jsfiddle http://jsfiddle.net/magedfarag/b4tsX/

+0

這裏是行動http://jsfiddle.net/magedfarag/b4tsX/的問題的jsfiddle –

回答

1

問題您不正確初始化您Employee實例:self是不確定的存在,你需要this。此外,alert(item.Name)將顯示功能,item.Name也可觀察到的(你解開只有self.newEmployee觀察到的,但是它的性能仍然可觀)。

Updated fiddle

+0

謝謝。你救了我。我多次查看代碼並忽略了這個愚蠢的錯誤。 –