我试图避免在dom-repeat
中多次调用相同的函数。
示例:
<template is="dom-repeat" items="..." as="column">
<template result="_myFunction(column, index)">
<div>Primary: [[result.primary]]</div>
<div>Secondary: [[result.secondary]]</div>
...
</template>
</template>
...
_myFunction(column, index) {
return { primary: "1", secondary: "2", ......}
}
但我无法找到正确的方法,因为我正在_myFunction(column, index)
的所有<div>
中呼叫$hosts = array (
0 => 'example/search?results1',
1 => 'thisone/search?results2',
2 => 'thesetoo/search?results3'
);
$counts = array (
0 => '3',
1 => '5',
2 => '7'
);
$results =array();
foreach ( $counts as $count ) {
$key_of_count = array_search( $count, $counts );
for ($i=0; $i < (int)$count; $i++) {
$results[$key_of_count][] = $hosts[$key_of_count];
}
}
echo "<pre>"; print_r($results); echo "</pre>";
。
如何避免多次调用该函数?
答案 0 :(得分:1)
尝试使用以下代码,其中带有DOM重复的聚合物自定义元素的工作示例,希望这对您有用,
<dom-module id="your-template-container">
<template>
<template is="dom-repeat" items="{{data}}" as="column">
<div>Primary: [[column.primary]]</div>
<div>Secondary: [[column.secondary]]</div>
</template>
</template>
<script>
Polymer({
is: 'your-template-container',
ready: function() {
// Sample object data is below
this.data = [
{primary: 1, secondary: 2},
{primary: 1, secondary: 2},
{primary: 1, secondary: 2}
];
}
});
</script>
</dom-module>
<!-- THE FOLLOWING WILL RENDER YOU POLYMER CUSTOM ELEMENT WITH DOM REPEAT-->
<your-template-container></your-template-container>
答案 1 :(得分:1)
我找到了一种避免使用缓存多次调用_myFunction
的方法:
Before the `dom-repeat`:
execute the function
cache the result in an object
In the `dom-repeat`
use the cached-object to retrieve the value
奖励:使用备忘录也可能有效