简体   繁体   English

如何使用可观察到的敲除作为json对象

[英]how to use knockout observable as json object

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 和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());

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. self.addEmployee方法中,当我使用该项目时,尽管该项目已添加到列表中并显示在网格中,但我仍为空值。

edit: the problem in jsfiddle http://jsfiddle.net/magedfarag/b4tsX/ 编辑:jsfiddle中的问题http://jsfiddle.net/magedfarag/b4tsX/

You are initializing your Employee instances incorrectly: self is undefined there, you need this . 您错误地初始化了Employee实例:那里的self未定义,您需要this Also, alert(item.Name) will display a function, as item.Name is also an observable (you're unwrapping only the self.newEmployee observable, but its properties remain observables). 另外, alert(item.Name)将显示一个函数,因为item.Name也是可观察的(您只展开了self.newEmployee可观察的self.newEmployee ,但其属性仍然是可观察的)。

Updated fiddle . 更新小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM