如何格式化资源字符串?

时间:2015-02-18 19:32:39

标签: javascript jquery string-formatting

到目前为止我有这个片段:

    resetSettings: function (type, showConfirm, OnImageLoad) {
        if (showConfirm) {
            var msg = "";
            Localization.GetBrowserLocalResource("ConfirmMsg", function (key, value) {
                msg = value;
            });

但是我想用这样的东西来格式化它,在那里我传入类型来格式化字符串:

Localization.stringFormat(getString(Localization.GetBrowserLocalResource("ConfirmMsg", type)));

但我需要在该方法中使用函数(key,value)格式化字符串。我怎么做?

编辑:

GetBrowserLocalResource的定义:

    var browserLocalResources = {};

    // callback =  callback(key,value)
    GetBrowserLocalResource: function (key, callback) {

        var val = "--no--resource";

        if (browserLocalResources != null) {

            if (browserLocalResources.hasOwnProperty(key)) {
                val = browserLocalResources[key];
                callback(key, val);
            } else {
                Localization.GetResourceFromServer(key, callback);
            }

        } else {
            AjaxLog.WriteLog("error: GetBrowserLocalResource", "browserLocalResources == null");
        }

        return (val);
    },

我如何使用stringFormat?

stringFormat是:

stringFormat: function () {

            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i++) {       
                var reg = new RegExp("\\{" + i + "\\}", "gm");             
                s = s.replace(reg, arguments[i + 1]);
            }

            return s;
        }

这样的东西?:

if (showConfirm) {
                var msg = "";
                stringFormat(Localization.GetBrowserLocalResource("ConfirmMsg"), type, function (key, value) {
                    msg = value;
                });

1 个答案:

答案 0 :(得分:1)

听起来您希望能够使用可选的第二个参数调用Localization.GetBrowserLocalResource。您必须修改该功能。这应该让您开始为方法定义可选参数:

// type is optional
// callback =  callback(key,value)
GetBrowserLocalResource: function (key, type, callback) {

    if (typeof callback === 'undefined' && typeof type === 'function') {
        callback = type;
        type = void 0;
    }

    // ...
},

(当然,如果type不是可选的,但始终是必需的,那么只需添加参数并且不添加类型检查)

完成此更改后,您可以调用以下方法:

resetSettings: function (type, showConfirm, OnImageLoad) {
    if (showConfirm) {
        var msg = "";
        Localization.GetBrowserLocalResource("ConfirmMsg", type, function (key, value) {
            msg = Localization.stringFormat(GlobalObjects.getString(value);
        });