Knockout.js,映射插件和moment.js-格式化/映射JSON日期 [英] Knockout.js, mapping plugin and moment.js - formatting/mapping json dates

查看:170
本文介绍了Knockout.js,映射插件和moment.js-格式化/映射JSON日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有映射插件的kickout.js.我正在获取一些json数据,并使用映射插件将其映射到我的html中.

I am using knockout.js with the mapping plugin. I am getting some json data and using the mapping plugin to map it into my html.

在json数据中,我需要使用映射插件将json格式的日期映射到html中.是否可以使用moment.js格式化日期,然后允许映射插件将其映射到html中?如何获取json日期,将其重新格式化为可读日期,然后将其映射到html中?

In the json data is a json formatted date that I need to map into the html using the mapping plugin. Is it possible to use moment.js to format the date and then allow the mapping plugin to map it into the html? How do I get the json date, reformat it to a readable date and map it into the html?

// Here is my json formatted date
"DueDate":"\/Date(1362124800000)\/"

// Here's my data model
var viewModel;
$.getJSON('/myJsonData', function (data) {
    viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);

// moment.js format date from json - how can this be passed to the ko.mapping?
    var mo = moment("\/Date(1362124800000)\/").format("MMM Do YY");
});

推荐答案

这是一个替代答案,它使用了

Here's an alternative answer, that utilizes a custom binding. You use it in your View like this:

<span data-bind="textualDate: DueDate"></span>

自定义绑定代码如下:

ko.bindingHandlers.textualDate = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        var valueUnwrapped = ko.utils.unwrapObservable(valueAccessor());
        var textContent = moment(valueUnwrapped).format("MMM Do YY");
        ko.bindingHandlers.text.update(element, function() { return textContent; });
    }
};

这很方便,因为您可以将此绑定用于所有Date可观察对象,而不仅仅是DueDate.例如,假设您的模型使用其他日期扩展,则可以轻松地执行此操作,而无需修改视图模型:

This is convenient because you can use this binding for all Date observables, not just DueDate. For example, suppose your model gets extended with other dates, you can easily do this without having to modify your view model:

<span data-bind="textualDate: StartDate"></span>
<span data-bind="textualDate: RevisedDate"></span>
<span data-bind="textualDate: DueDate"></span>
<span data-bind="textualDate: WeWillGetSuedPassedThisDueDate"></span>

您可以查看此jsfiddle 以获得有效的演示.

You can check out this jsfiddle for a working demo.

这篇关于Knockout.js,映射插件和moment.js-格式化/映射JSON日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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