KnockoutJS:绑定到具有非法名称的对象

时间:2012-10-11 04:10:05

标签: javascript jquery xml json knockout.js

我正在开发的项目需要大量复杂的XML文件,所以我将它们转换为SimpleXML数组,JSON对其进行编码并通过Ajax将其传递给Knockout。

问题在于,每个属性都有属性,SimpleXML会将其推入名为@attributes的对象中。当我尝试像myObject().@attributes.Name那样绑定它时,我收到错误

Message: SyntaxError: Unexpected token ILLEGAL;
Bindings value: text: alertObj().@attributes.Name 

我尝试了'@attributes', ['@attributes'], [@attributes]但没有任何效果。我也尝试了各种转义字符和unicode转义。

这就是json的样子:

        var alertObject =
            {
                "@attributes":
                    {
                        "DescriptionContentType":"text\/plain",
                        "Description":"",
                        "IsActive":"true",
                        "Name":"Apache Requests Per Interval"
                    },
                "Frequency":
                    {
                        "PeriodInSeconds":"60"
                    },
                "MetricLevelNotification":"false",
                "AlertTriggerMode":"2",
                "CautionActionDelay":"0",
                "DangerActionDelay":"0",
                "CautionActionList":
                    {
                        "ActionID":
                            {
                                "ManagementModuleName":"Base Module",
                                "ConstructName":"Base SMTP Mail Action"
                            }
                    },
                "DangerActionList":
                    {
                        "ActionID":
                            {
                                "ManagementModuleName":"Base Module",
                                "ConstructName":"Base SMTP Mail Action"
                            }
                    },
                "MetricGroupingID":
                    {
                        "ManagementModuleName":"Base Module",
                        "ConstructName":"Apache Requests Per Interval"
                    },
                "AlertCombineOperator":"1",
                "AlertCompareOperator":"2",
                "CautionTargetValue":"2000",
                "DangerTargetValue":"15000",
                "CautionMinNumPerPeriod":"3",
                "CautionAlertPeriod":"6",
                "DangerMinNumPerPeriod":"1",
                "DangerAlertPeriod":"1"
            };

我想避免以任何方式改变结构和名称。

我怎样才能让它工作?

2 个答案:

答案 0 :(得分:5)

那是因为它不是有效的javascript变量名:

  

标识符必须以$,_或Unicode中的任何字符开头   类别“大写字母(Lu)”,“小写字母(Ll)”,   “Titlecase letter(Lt)”,“Modifier letter(Lm)”,“Other letter(Lo)”,   或“字母编号(Nl)”。

来自http://mathiasbynens.be/notes/javascript-identifiers

变量名不能以@开头,因此您会看到错误。附加单引号,括号或其他任何内容都没有意义。变量名无效,您需要更改从服务器返回数据的方式。

答案 1 :(得分:1)

我遇到了类似的问题,我完全同意你绝对应该改变从服务器返回数据的方式。但是,如果您实际上无法控制数据或暂时无法控制数据,您可以使用以下方式呈现所需内容:

$data['@attributes'].Name