简体   繁体   中英

polymer binding a function result inside template

I'm trying to avoid calling multiple times the same function in a dom-repeat .

Example:

<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", ......}
}

But I can't find the correct way of doing this, for the moment I'm calling _myFunction(column, index) in all my <div> s.

How to avoid calling the function multiple times ?

Try with the following code, Its working example of polymer custom element with DOM repeat, hope this will work for you,

<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>

I found a way to avoid calling _myFunction multiple times using cache:

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

Bonus: using memoization might also work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM