如何建立在非全局语言环境中工作的“时刻"功能? [英] How can I build a 'moment' function that works in a non-global locale?

查看:42
本文介绍了如何建立在非全局语言环境中工作的“时刻"功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用MomentJS,如有必要,我可以使用.locale(或在较早版本中为.lang)在特定时刻实例(而不是全局)上设置区域设置.我该如何创建一个等效于moment(它的所有42个签名)的函数,该函数始终在与全局语言不同的特定语言环境中工作?

With MomentJS, if necessary I can set a locale on a specific moment instance (rather than globally) using .locale (or .lang in older versions). How can I create a function equivalent to moment (all 42 signatures of it) that always works in a specific locale that's different from the global?

我在Web项目中有一个子模块,该子模块必须使用自定义语言环境.我们不希望在此特定子模块之外使用此语言环境,但我们希望在该子模块中内部一致地使用该语言环境.因此,我基本上希望像moment一样可以调用的moduleMoment(或其他任何东西),但是它可以在自定义语言环境中使用.有内置的方法吗?

I have a submodule within a web project that has to work with a custom locale. We don't want this locale used outside this particular submodule, but we want it used consistently within that submodule. So I basically want a moduleMoment (or whatever) that I can call just like moment, but which works in the custom locale. Is there any built-in way to do that?

注意:我不是在说不是在谈论更改现有实例的语言环境,而是在打电话给moment使用其全局语言环境 other 的语言环境(具有各种不同的签名).所以这行不通:

Note: I'm not talking about changing the locale of an existing instance, I'm talking about calling the moment function (in all its various different signatures) using a locale other than its global locale. So this won't work:

var m = moment(args).locale(localeId);

...因为将在全局语言环境中处理args,然后事后在实例上更改语言环境,为时已晚.

...because the args will be processed in the global locale, and then the locale gets changed on the instance after the fact, which is too late.

推荐答案

我能找到的唯一方法是拥有一个临时设置区域设置的函数,调用moment,然后将区域设置恢复为上一个一个,像这样:

The only way I can find to do it is to have a function that temporarily sets the locale, calls moment, then sets the locale back to the previous one, like this:

function moduleMoment() {
    var prevLocaleId, m;

    prevLocaleId = moment.locale();
    try {
        moment.locale(customLocaleId);
        m = moment.apply(this, arguments);
        return m;
    } finally {
        moment.locale(prevLocaleId);
    }
}

或者可以将其添加到moment中,如下所示:

Or one could add it to moment, like this:

moment.localized = function(locale) {
    var prevLocaleId, m, args;

    prevLocaleId = moment.locale();
    try {
        moment.locale(locale);
        m = moment.apply(this, Array.prototype.slice.call(arguments, 1));
        return m;
    } finally {
        moment.locale(prevLocaleId);
    }
};

这篇关于如何建立在非全局语言环境中工作的“时刻"功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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