【问题标题】:Why apply can't be used inside the jQuery template为什么在jQuery模板内部不能使用apply
【发布时间】:2012-10-15 11:14:12
【问题描述】:

我的示例 JSON 和 js:

function foo1(a) { return a*1.5;} //NOTE: foo1 accept one parameter
function foo2(a,b) { return a*1.5 + b;} //NOTE: foo2 accept two parameter
var arr=[ {func:foo1, para:[10]}, {func:foo2, para:[10,20]} ];

我的 jQuery 模板(不工作):

<script id="template1" type="text/x-jquery-tmpl">
        ${$item.data.func.apply(this,$item.data.para)}
</script>

调用模板:

 $('#template1').tmpl(arr).appendTo('#mycontainer');

我的问题:

  • 我有不同的函数接受不同数量的参数(我无法更改函数的参数数量)
  • 所以我想在 'func' 中传递函数名,在 'para' 中传递参数(作为数组),并使用“apply”方法从 jQuery 模板内部调用该方法
  • 但如果我在函数后使用 apply(如 $item.data.func.apply),则会引发“未定义”错误

更多观察(工作):

  • 如果我调用 $item.data.func(10) 或 $item.data.func(10,20) 之类的方法,它会起作用
  • 在我想调用方法typeof $item.data.func的时候返回'function'

请帮忙

【问题讨论】:

    标签: javascript jquery jquery-templates


    【解决方案1】:

    如果表达式是函数类型,似乎是 jQuery 模板框架本身使用 apply 来调用。这使得事情阻止在 jQuery 模板中使用 apply 来调用方法。

    所以这是我的技巧,我引入了一个通用的通用方法调用器,比如

    模板:

    <script id="template1" type="text/x-jquery-tmpl">
        ${genericTrigger($item.data.func, $item.data.para)}
    </script>
    

    JS:

    function genericTrigger(func, para) {
        // This need to check, as some unexpected call is coming to this 
        // without passing value
        if (typeof func != 'undefined' && typeof func == 'function') 
        {
           return func.apply(this, para);
        }
    }
    
    
    var arr=[ {func:foo1, para:[10]}, {func:foo2, para:[10,20]} ];
    $('#template1').tmpl(arr).appendTo('#mycontainer');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-09
      • 2014-06-18
      • 2018-10-04
      • 2020-04-05
      • 2011-07-03
      • 2019-08-14
      • 1970-01-01
      • 2018-11-17
      相关资源
      最近更新 更多