0

在处理使用包含(视图和部分视图)的布局页面的 ASP.NET MVC 应用程序时,我通常在布局页面的顶部声明一个 javascript var,我在视图或部分视图中分配一个 js 匿名函数加载文档后将立即调用的视图。一旦页面从服务器返回,这样的事情和这个顺序:

 <!-- top of layout page : static -->

 <!-- ver jquery for bootstrap -->
<script src="@Url.Content("~/Scripts/bootstrap/jquery-1.9.1.js")" type="text/javascript"></script>

 <script type="text/javascript">

 //define app's js namespace
 var myApp = {};

 //placeholder for anon func
 myApp.initLoadFunc = null;

 </script>


 <!-- Child View : dynamically added (or not) depending on current view -->
<script type="text/javascript">

//for this view, I want to run this on document load
myApp.initLoadFunc = function() { //do something... }
</script>
<!-- end child view -->


<!-- bottom of Layout page : static -->
<script type="text/javascript">

  $(document).ready(function () {

        //run init function if populated...
        if (myApp.initLoadFunc != null) {
            myApp.initLoadFunc();
        }
    });


</script>

我的问题是:如果我想在解析时定义和分配多个函数或从其他子视图添加到 anon 函数的主体而不声明额外的 var 占位符怎么办?我不想做任何不稳定的评估电话。有没有办法链式添加?我也许可以定义一个 js 数组并填充函数,但我认为有一种更简洁的方法可以完成此任务。不知何故使用“这个”?有什么解决办法吗?

4

1 回答 1

0

经过一番思考,我可以使用反射来调用添加到已定义 js 对象的所有函数。@vorrtex 提出了一个很好的观点,即不需要创建空属性来分配匿名函数,因为这些将在 JS 中为您创建,但在这种情况下,它可以帮助我将动态添加的函数与其他属性/方法分开不应在文档加载时调用。这很好用,满足我的要求:

<!-- top of layout page : static -->     

 <script type="text/javascript">

 //define app's js namespace
 var myApp = {};

 //empty func for all added anon funcs, to separate those NOT to be invoked on load
 myApp.initLoadFuncs = {};

 </script>


 <!-- Child View (1) : dynamically add anon func to be run on load -->
<script type="text/javascript">

//for this view, I want to run this on document load
myApp.initLoadFuncs.view1Func = function() { //do something... }
</script>

<!-- end child view -->


 <!-- Child View (2) : add another anon func to be run on load -->
<script type="text/javascript">

//I want to run this also onload if this view is included
myApp.initLoadFuncs.view2Func = function() { //do something else... }
</script>

<!-- end child view -->


<!-- bottom of Layout page : static -->
<script type="text/javascript">

  $(document).ready(function () {

        if (myApp.initLoadFuncs) {

            //enumerate func properties, use reflection to determine if function, and invoke
            for (var m in myApp.initLoadFuncs) {

                if (typeof(myApp.initLoadFuncs[m]) == "function") {

                    myApp.initLoadFuncs[m]();
                }
            }
        }


    });


</script>
于 2013-11-12T23:08:22.113 回答