【问题标题】:Is it possible to wrap a single jQuery document ready event around a ScriptBundle in Asp.Net MVC?是否可以在 Asp.Net MVC 中围绕 ScriptBundle 包装单个 jQuery 文档就绪事件?
【发布时间】:2015-01-06 14:45:55
【问题描述】:

为了避免为 Asp.Net MVC ScriptBundle 中的每个文件多次调用 jQuery .ready() 事件,是否可以将 ready 事件包装在整个包中?

以下每个文件都包含 $( document ).ready(function() { } 代码,其中包含 JavaScript 代码...

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js",
                        "~/Scripts/core.js",
                        "~/Scripts/application.js",
                        "~/Scripts/controls.js",
                        "~/Scripts/custom.js"));

我可以创建两个js文件,一个包含$(document).ready(function(){,另一个只包含一个右括号。然后将这些文件添加到开头和结尾现有的捆绑包,但有更好的方法吗?

A similar question 已被要求使用 CoffeScript 连接文件,但我无法轻松地将解决方案转换为 Asp.Net 捆绑。

【问题讨论】:

  • 你不能简单地这样做。为此,您需要在 JS 中使用模块模式

标签: jquery asp.net-mvc bundling-and-minification


【解决方案1】:

如果您正在查看您编写的 JavaScript 文件(不是 jquery-{version}.js),请创建一个可从您在页面上调用的文件外部公开访问的方法。

var Application = (function () {
    // All your code

    function init() {
        // All your code that you have inside $(document).ready()
    }

    return {
        init: init
    };
}());

对所有文件执行上述操作,然后在任何需要它的页面上,或者在您的 _Layout 页面中(如果它要在每个页面上运行)在底部有以下内容

<script type="text/javascript">
    $(document).ready(function () {
        Application.init();
        // etc for the other files.
    });
</script>

【讨论】:

  • 这种方法将关闭该文件中其他所有内容的范围。因此请注意,如果您确实在这些文件中有要在文件之外访问的内容,则需要将其添加到 return 块中,例如 init.xml 。这是一个好习惯,因为它可以最大限度地减少您在全球空间中的足迹。
  • 我认为这是 JavaScript 模块模式?是否有您推荐的在线教程让自己跟上进度?如果您没有时间发布任何我理解的内容,并感谢您迄今为止的帮助。
  • 正确。我没有使用教程,而是阅读了 Mark E. Daggett 的“Expert Javascript”一书,以学习大量编写更简洁、更可扩展的 JavaScript 的技能和实践。当然,这是在 JavaScript: The Good Parts 之后。
  • 太棒了。我去看看。
猜你喜欢
  • 1970-01-01
  • 2011-02-04
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多