Niels
Niels

Reputation: 223

Notify polymer about new function result

How can I tell Polymer 2.0 about a change of a function result even though the input command did not change? Consider this small example, which modifies my-view1 of the basic polymer-2-starter-kit:

<dom-module id="my-view1">
  <template>
    <style include="shared-styles">
      :host {
        display: block;

        padding: 10px;
      }
    </style>

    <div>[[getText(node)]]</div>

    <paper-button on-tap="changeElements">Change elements</paper-button>
  </template>

  <script>
    class MyView1 extends Polymer.Element {
      static get is() { return 'my-view1'; }

      static get properties() {
        return {
           node: {
            type: Number,
            value: 0
          },

          node2: {
            type: Number,
            value: 5
          }
        }
      }

      changeElements() {
        this.node2 += 1;
        console.log(this.getText(0));
      }

      getText(item) {
        return this.node2;
      }

    }

    window.customElements.define(MyView1.is, MyView1);
  </script>
</dom-module>

When I click the button, node2 and thus the result of getText changes which is shown in the console. However, the depicted value constantly remains at the initial value 5. I guess, since node does not change, the change is not handled. Is there a possibility to notify Polymer about the change of the function result? Something like notifyPath for functions or similar? Or do I need to set some flags or something like that?

While I'm aware that this minimal example would easily be solved by just outputting node2 instead of using getText(node), it's a lot more complex in my regular project where a function computes the output based on different factors.

Upvotes: 0

Views: 149

Answers (2)

Rickard Elim&#228;&#228;
Rickard Elim&#228;&#228;

Reputation: 7591

For ...

<div>[[getText(node)]]</div>

... add ...

<div>[[getText(node, node2)]]</div>

and use this.set('node2', number) to send an event to [[getText]] so it updates. Setting variables with this.[variable] = XXX usually wont update anything.

Get into this habit of using this.set, otherwise you will get in real trouble when you're starting to use dom-repeat and dom-if.

Upvotes: 1

Jeff Machamer
Jeff Machamer

Reputation: 942

You are using a computed binding with the node property, which means it will only get recomputed when node is updated. You would need to bind with node2 if you want it to fire when node2 is updated. (or bind to node and node2.. )

A bit of an odd example since you are binding to a value that you aren't using.

Upvotes: 0

Related Questions