难道ko.toJSON()与日期的工作? [英] Does ko.toJSON() work with dates?

查看:114
本文介绍了难道ko.toJSON()与日期的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net mvc的页面上knockoutjs。我使用AJAX调用 ko.toJSON(视图模型),然后回发到使用jQuery的服务器,结果坚持的一种形式返回给服务器。所有的视图模型属性都成功序列化,除了被持久化一个空的对象Javascript的日期。

I am using knockoutjs on an asp.net mvc page. I am using ajax to persist a form back to the server by calling ko.toJSON(viewModel) and then posting the results back to the server using jQuery. All of the properties on the view model are successfully serialized except for the Javascript date which is persisted as an empty object.

声明:

var viewModel = {
    startTime: ko.observable(),
    type: ko.observable(),
    durationInMinutes: ko.observable(),
    notes: ko.observable()
};

保存数据:

var postData = ko.toJSON(viewModel); 
$.ajax({
    url: "/data",
    type: "POST",
    data: postData,
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function () {
        console.log('success!');
    },
    error: function () {
        console.log('fail!');
    }
});

viewModel.startTime()的执行console.log值是:

The console.log value of viewModel.startTime() is:

日期{星期二2011年5月10日11:30:00 GMT-0500(中部夏令时间)}

第1行后,保存数据,POSTDATA的值是:

After line 1 of Save Data, the value of postData is:

{
    "startTime": {},
    "type": "1",
    "durationInMinutes": "45",
    "notes": "asfasdfasdfasdfasdfasdfasdfas",
    "displayableStartTime": "10-May 11:30"
}

如果我展开的第1行的保存数据

If I expand line 1 of Save Data to

var jsonEvent = ko.toJS(viewModel);
jsonEvent.startTime = viewModel.startTime();
var postData = JSON.stringify(jsonEvent);

POSTDATA的值是:

The value of postData is:

{
    "startTime": "2011-05-10T16:30:00.000Z",
    "type": "1",
    "durationInMinutes": "45",
    "notes": "asfasdfasdfasdfasdfasdfasdfas",
    "displayableStartTime": "10-May 11:30"
}

谁能解释可能什么以及如何我也许能得到knockoutjs处理日期对象?

Can anyone explain what might be going on and how I might be able to get knockoutjs to handle the date object?

推荐答案

鉴于目前问题ko.toJS和日期,其中一个方案是创建包含所需的服务器来处理实际价值dependentObservable。

Given the current issue with ko.toJS and dates, one option would be to create a dependentObservable containing the real value that you want the server to deal with.

是这样的:

var viewModel = {
    startTimeForInput: ko.observable(),
    type: ko.observable(),
    durationInMinutes: ko.observable(),
    notes: ko.observable()
};

viewModel.startTime = ko.dependentObservable(function() {
    return this.startTimeForInput().toJSON();
}, viewModel);

ko.applyBindings(viewModel);

现在,当你调用 ko.toJSON 您将获得的startTime 正确的值,该服务器可以使用。

Now, when you call ko.toJSON you will get the startTime with the correct value that the server could use.

有关旧的浏览器,像 json2.js 将包括.toJSON为Date对象。

For older browsers, something like json2.js would include the .toJSON for Date objects.

这篇关于难道ko.toJSON()与日期的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆