从cshtml调用命名空间中的函数

时间:2016-08-31 16:28:31

标签: typescript

我发现了一些与Typescript和名称空间完全混淆的东西。如果我将一个Typescript函数放在命名空间中并在onclick中调用该函数,那么IE中的调用将失败,但在Chrome和Firefox中可以使用。

即。打字稿

namespace @idARPanelHdrWithHash
{
    export function ChangeText(id : string)
    {
    }
}

CSHTML:

<p id="@idARPanelHdr"
   class="UserARViewMore collapsed"
   onclick="ChangeText('@idARPanelHdrWithHash')"
   data-toggle="collapse"
   data-target="@idARPanelWithHash">
   VIEW MORE
</p>

如果我改为onclick to“AdminEditPages.ChangeText('@ idARPanelHdrWithHash'),它可以在IE浏览器中运行,但不适用于Firefox或Chrome。

如果我在IE中打开调试工具,请在调用“。”时调用控制台并输入AdminEditPages。我得到所有类型的东西,但在Chrome或Firefox中没有。很明显,Firefox或Chrome中不存在名称空间。

我错过了什么?

提前致谢,

Adam Benson。

1 个答案:

答案 0 :(得分:0)

First the name you are using for the namespace is not a valid identifier name and the code won't compile to javascript.

Just lose the @.

namespace idARPanelHdrWithHash
{
    export function ChangeText(id : string)
    {
    }
}

When it compiles you can see what the generated Javascript is.

var idARPanelHdrWithHash;
(function (idARPanelHdrWithHash) {
    function ChangeText(id) {
    }
    idARPanelHdrWithHash.ChangeText = ChangeText;
})(idARPanelHdrWithHash || (idARPanelHdrWithHash = {}));

If that cshtml will eventually become html the correct way of calling the ChangeText function would be.

<p id="@idARPanelHdr"
   class="UserARViewMore collapsed"
   onclick="idARPanelHdrWithHash.ChangeText('@idARPanelHdrWithHash')"
   data-toggle="collapse"
   data-target="@idARPanelWithHash">
   VIEW MORE
</p>

For quick reference you can use the TypeScript playground to see what TypeScript code compiles to. Like this.