从 ASP.NET Webform 代码后面的 Javascript 命名空间设置变量
我正在尝试清理一些较旧的代码,它当前使用 ScriptManager 设置的变量在 Javascript 代码中用于显示/隐藏页面的部分内容。
这些变量目前只是 _showNameDiv
等。
我想将这些全部放在一个公共命名空间中,以使事情变得更清晰一些,例如 MyCompany.Toggles.ShowNameDiv
。
我尝试创建一个命名空间
var MyCompany = {
Toggles: {}
}
并在后面的代码中执行此操作:
JavaScriptRegistrar javaScriptRegistrar = GetJavaScriptRegistrar();
javaScriptRegistrar.Register("MyCompany.Toggles.ShowNameDiv", true);
但我只在该变量上得到 'undefined'
。 (GetJavaScriptRegistrar 是 ScriptManager 的包装器)。
有办法做我想做的事吗? 我是否以错误的方式处理这个问题? 有没有更好的替代方案可以给我带来同样的好处?
请记住,这是旧代码,我无法重写整个页面。我正在尝试采取渐进的步骤,我可以将其用作可以向同事展示的示例。
I am trying to clean up some older code, and it currently uses variables set with ScriptManager for use in the Javascript code to show/hide parts of the page.
The variables are currently just _showNameDiv
, etc.
I'd like to put these all onto a common namespace, to make things a little bit cleaner, such as MyCompany.Toggles.ShowNameDiv
.
I tried to create a namespace
var MyCompany = {
Toggles: {}
}
And within the code behind do this:
JavaScriptRegistrar javaScriptRegistrar = GetJavaScriptRegistrar();
javaScriptRegistrar.Register("MyCompany.Toggles.ShowNameDiv", true);
But I only get 'undefined'
on that variable. (GetJavaScriptRegistrar is a wrapper for ScriptManager).
Is there a way to do what I am trying to do?
Am I going about this the wrong way?
Is there a better alternative that will get me the same benefit?
Keep in mind this is old code, and I cannot do a whole page rewrite. I am trying to make an incremental step that I might use to use as an example that I can show to my coworkers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果不知道这些代码到底是做什么的(特别是 JavascriptRegistrar),就很难找出问题所在。
一个可能的问题可能是您声明的 javascript“命名空间”的范围。
通过使用“var”关键字,您不会使命名空间成为全局的,它仅在其定义的闭包中定义。
我想 JavascriptRegistrar 类注册的 javascript 代码需要一个全局变量,但没有找到任何变量,因此它返回
undefined
。这里有一段代码可以在全球范围内“暴露”你的变量:
Well it's difficult to figure what could be the problem without knowing what those pieces of code exactly do (expecially JavascriptRegistrar).
One possible problem is maybe the scope of the javascript "namespace" you declare.
By using the "var" keyword, you're not making the namespace global, it's only defined in the closure it's defined into.
I suppose the javascript code that the JavascriptRegistrar class registers expects a global variable and does not find any so it returns
undefined
.Here a piece of code to "expose" gloabally you're variable: