在下面的代码中,我为车把定义了一个自定义的中断帮助器。使用for循环开发了自定义中断功能,以循环访问数组对象。但是,中断帮助程序本质上不是通用的,而是特定于特定数组的。如何定义通用的自定义中断助手?
<!-- required handlebars: -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<!-- handlebars template: -->
<script id="handlebars-demo" type="text/x-handlebars-template">
{{#break students}}
{{name}} has passed in {{passingYear}}.<br>
{{/break}}
</script>
<div id="placeholder"></div>
<script>
//context object:
var context = {
"students": [
{
"name": "student1",
"passingYear": 2016
},
{
"name": "student2",
"passingYear": 2018
},
{
"name": "student3",
"passingYear": 2013
},
{
"name": "student4",
"passingYear": 2019
}
]
}
//defining customized "break" helper in handlebars:
Handlebars.registerHelper("break", function(data,options) {
var len = data.length;
var returnData = "";
//custom break function:
for (var i = 0; i < len; i++) {
if(data[i].passingYear>2015){
document.write(returnData + options.fn(data[i]));
} else {
document.write(returnData + options.fn(data[i]));
i=len+1;
}
}
});
//set variable template to handlebars-demo id in test.html:
var template = $('#handlebars-demo').html();
// Handlebars compiles the above template variable into a templateScript:
var templateScript = Handlebars.compile(template);
// context object is passed to above templateScript:
var html = templateScript(context);
//setting html to output:
$("#placeholder").append(html);
</script>
答案 0 :(得分:0)
var context = {
"students": [{
"name": "mrinal",
"passingYear": 2013
},
{
"name": "raman",
"passingYear": 2016
},
{
"name": "John",
"passingYear": 2018
}
]
}
var context2 = ["mrinal","raman","John"];
Handlebars.registerHelper("break", function(array, field, operator, breakvalue, options) {
var arrayLength = array.length;
var returnData="";
var fieldValue = '';
for (var i = 0; i < arrayLength; i++) {
if (field === '.') {
fieldValue=array[i];
} else {
fieldValue=array[i][field];
}
if ((operator == "eq" && fieldValue == breakvalue) ||
(operator == "ne" && fieldValue != breakvalue) ||
(operator == "gt" && fieldValue > breakvalue) ||
(operator == "le" && fieldValue <= breakvalue) ||
(operator == "ge" && fieldValue >= breakvalue) ||
(operator == "lt" && fieldValue < breakvalue)) {
returnData = returnData + options.fn(array[i]);
} else {
return returnData;
}
}
return returnData;
});
var template = $('#handlebars-demo').html();
var templateScript = Handlebars.compile(template);
var html = templateScript(context2);
$("#placeholder").append(html);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<script id="handlebars-demo" type="text/x-handlebars-template">
{{#break this '.' 'ne' 'raman'}}{{this}} has passed.<br>{{/break}}
</script>
<div id="placeholder"></div>