Knockout JS - 将类序列化为 JSON
我正在学习 Knockout JS(很棒的框架!顺便说一句,我来自 Silverlight,MVVM powa),我认为我正在阻止一个简单的事情。
我有一个像这样的 User
类:
var User = function () {
this.Login = ko.observable();
this.FirstName = ko.observable();
this.LastName = ko.observable();
this.Password = ko.observable();
this.Email = ko.observable();
};
和一个像这样的 ViewModel:
var UsersPage = function () {
/*
* Properties
*/
this.self = this;
this.users = ko.observableArray([new User()]);
this.newUser = ko.observable(new User());
/*
* Methods
*/
this.saveUser = function () {
alert(ko.ToJSON(this.newUser()));
};
};
在 HTML 中,我有一个绑定到“newUser”属性的简单表单。当我提交表单时,我想序列化 JSON 中的属性以将其传递给 WCF 服务。 ko.ToJSON 似乎不起作用。我尝试了多种方法,但没有得到我期望的结果。
所以,我的问题是:如何将我的 User 属性序列化为 JSON?
这是一个 JSFiddle 来重现它: http://jsfiddle.net/ZfSbR/5/
I'm learning Knockout JS (awesome framework! By the way, I'm from Silverlight, MVVM powa) and I think I'm blocking on a simple thing.
I have a class User
like this :
var User = function () {
this.Login = ko.observable();
this.FirstName = ko.observable();
this.LastName = ko.observable();
this.Password = ko.observable();
this.Email = ko.observable();
};
And a ViewModel like this :
var UsersPage = function () {
/*
* Properties
*/
this.self = this;
this.users = ko.observableArray([new User()]);
this.newUser = ko.observable(new User());
/*
* Methods
*/
this.saveUser = function () {
alert(ko.ToJSON(this.newUser()));
};
};
In the HTML, I have a simple form bound to the "newUser" property. When, I submit my form, I want to serialize the property in JSON to pass it though to a WCF service. The ko.ToJSON
doesn't seem to work. I tried several methods, but I am not getting the results I expect.
So, my question is: How do I serialize my User property to JSON?
Here is a JSFiddle to reproduce it : http://jsfiddle.net/ZfSbR/5/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码存在几个问题。
ko.toJSON()
而不是ko.ToJSON()
(请参阅 文档)。this.self = this
应该是var self = this
- 您不需要引入self
作为属性。self
而不是this
,因为this
可能指向不同的对象而不是视图模型本身。data-bind
中使用newUser().property
而不是newUser.property
。此处是修改后的代码。
There are several problems with your code.
ko.toJSON()
and notko.ToJSON()
(see documentation).this.self = this
should bevar self = this
- you don't need to introduceself
as the property.self
instead ofthis
in view-model's methods, becausethis
may point to different object and not view-model itself.newUser().property
in thedata-bind
instead ofnewUser.property
.HERE is the modified code.