knockout.js - 使用 moment.js 格式化 Breeze 检索到的日期。 Hot Towel 模板

标签 knockout.js breeze hottowel momentjs

我一直在关注 John Papa 的 Hot Towel 教程,我有一个看起来像这样的 c# 类:

public class Lead
{
    public int LeadId { get; set; }
    public DateTime? LastContactMade { get; set; }
    public DateTime? LastContactAttempt { get; set; }
}

我正在使用 breeze 检索客户端中的数据,但我不知道如何使用 moment.js 和 knockout.js 格式化日期。当我使用以下 knockout 绑定(bind)显示未格式化的日期时:

<section data-bind="foreach: leads">
    <span data-bind="text: lastContactMade"></span>
    <span data-bind="text: lastContactAttempt"></span>
</section>

日期以下列格式显示:

Wed Feb 27 2013 03:28:00 GMT-0800 (Pacific Standard Time)

当我尝试使用 moment.js 格式化它们时,如下所示:

<section class="article-list" data-bind="foreach: leads">
    <span data-bind="text: moment(lastContactMade).format('l LT')"></span>
    <span data-bind="text: moment(lastContactAttempt).format('l LT')"></span>
</section>

结果输出如下所示:

NaN/NaN/0NaN 12:NaN AM

我还尝试通过以下方式在我的模型中的 LeadInitializer 中进行格式化(这是我更喜欢的):

function leadInitializer(lead) {
    lastContactAttempt = lead.lastContactAttempt;
    lastContactMade = lead.lastContactMade;
    lead.lastContactAttempt = ko.computed({
        read: function () {
            return moment(lastContactAttempt).format('l LT');
        },
        write: function () {
            return lastContactAttempt;
        }
    });
    lead.lastContactMade = ko.computed({
        read: function () {
            return moment(lastContactMade).format('l LT');
        },
        write: function () {
            return lastContactMade;
        }
    });
};

这样做,我仍然得到相同的输出:

NaN/NaN/0NaN 12:NaN AM

我已经在

阅读了这篇文章

Date formatting issues with Knockout and syncing to breeze.js entityAspect modified

但这似乎对我没有帮助。有人可以告诉我哪里出错了吗?

最佳答案

我想你只是忘了打开 Knockout observables:

// add parentheses here......................vv
<span data-bind="text: moment(lastContactMade()).format('l LT')"></span>
<span data-bind="text: moment(lastContactAttempt()).format('l LT')"></span>

当您使用 Breeze 加载实体时,所有属性都将创建为 Knockout 可观察对象。你可以直接在你的 data-bind Knockout 绑定(bind)中使用这些 observable,但是因为 moment.js 不知道如何处理 Knockout observable,你必须首先打开 observable 以获得纯 JavaScript日期值。

关于knockout.js - 使用 moment.js 格式化 Breeze 检索到的日期。 Hot Towel 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17117960/

相关文章:

javascript - Knockout JS - 将数据绑定(bind)到我的表

security - Breeze.js - 保护 IQueryable 调用

caching - Breeze Metadata request URL with cache bust

angularjs - ng-options 上的 Angular UI-Bootstrap 下拉按钮

javascript - 全局更改所有页面的 knockout 验证消息

javascript - KNockout JS - 自动重新加载 ajax 调用

javascript - iframe 内的 foreach 内的 knockout 模板

asp.net-web-api - Breeze - 对象 #<Object> 中的扩展结果没有方法 'getProperty' 查询失败

javascript - 当 Breeze 导航属性受权限控制时访问它们

breeze - 我可以将breeze.js 与SQLite 或本地数据库一起使用吗?