简体   繁体   中英

Pass function call as attribute in Polymer?

My Polymer element has an array attribute with anywhere from 1-10,000 items, so I need to generate it when the element is instantiated. However, I would really like to pass in an array using a function call or reference:

<script>
  function genArray(size){
    var a = [];
    for(var i = 0, count = size - 1; i < count; i++){
      a.push("domain" + count + ".tld");
    }
    return a;
  }
</script>

<my-element domains="genArray()"></my-element>

Or reference a global object.

<script>
  function genArray(size){
    var a = [];
    for(var i = 0, count = size - 1; i < count; i++){
      a.push("domain" + count + ".tld");
    }
    return a;
  }

  window.myArray = genArray(1000);
</script>

<my-element domains="window.myArray"></my-element>

I've tried variations on quote style ( "" vs '' ) brackets ( "{{genArray}}" ) and I even '{"array":window.myArray}' .

I understand that I could pass in the parameter or a reference to a global object and process them in a lifecycle callback. However, it would be much cleaner and simplify testing/deployment if I could pass in a call to an external function. Am I just screwed until template strings comes along in ES7?

Bindings only work within the Polymer environment, but there is a solution! Polymer provides a helper component called dom-bind that you can use anywhere in a page, even outside of a Polymer element:

<script>
  function genArray() {
      ...
  }

  window.myArray = genArray(1000);
</script>
<template is="dom-bind">
  <my-element domains="[[myArray]]"></my-element>
</template>

More documentation for this component can be found at https://www.polymer-project.org/1.0/docs/devguide/templates.html#dom-bind

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