如何构建JS函数链或在解析时添加到匿名函数体?

时间:2013-11-12 15:31:36

标签: javascript asp.net-mvc function syntax

当处理使用包含(视图和部分视图)的布局页面的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数组并填充函数,但我认为有一种更简洁的方法可以实现这一点。不知何故使用“这个”?任何解决方案?

1 个答案:

答案 0 :(得分:0)

经过一番思考,我可以使用反射来调用添加到定义的js对象的所有func。 @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>