Passing function as parameter to jQuery template

310 Views Asked by At

I'm trying to send a function as parameter to a jQuery template and display the first element returned by the function.

In the following example, data variable is a function and I'm trying to append first element returned. It's not a solution to store data into a variable because there are many cases when data is an array, not a function.

var template= ' {{each things}}{{if $index == 0}}<span>${this.Name}</span>{{/if}}{{/each}}';

$('.dropdownText').text(jq.tmpl(template, data));
1

There are 1 best solutions below

1
Shyam Babu On BEST ANSWER

I am not sure if i got the question rigt but if the problem is data can be a function or array you probably just have to do this

var selectedTemplate = ' {{each things}}{{if $index == 0}}<span>${this.Name}</span>{{/if}}{{/each}}';
function getData(data) {
 if (Array.isArray(data)) return data;
 if (typeof data === 'function') return data();
}
$('.dropdownText').text(UMT_jq.tmpl(selectedTemplate, getData(data)));