为什么不能在jQuery模板中使用

时间:2012-10-15 11:14:12

标签: javascript jquery jquery-templates

我的示例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 )则抛出'undefined'错误

更多观察(工作):

  • 如果我调用了$ item.data.func(10)或$ item.data.func(10,20)这样的方法,那么
  • 我想调用方法typeof $item.data.func返回'function'

请帮助

1 个答案:

答案 0 :(得分:0)

似乎是jQuery Template框架本身使用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');