Hedge
Hedge

Reputation: 16748

Trigger Polymer data-binding change programmatically?

I'm using Polymer's data-bindings to display structured data. Upon clicking a button I want to alter a data-item but the displayed {{item.name}} doesn't change.

What am I doing wrong in the following example?

I simplified as much as possible!

<template id="bind" is="dom-bind">
  <script>
    bind.changeName = function() {
      var repeater = document.querySelector('#repeater');
      repeater.items[0].name = 'New Name' //doesn't work
      repeater.set('items#0.name', 'Another New Name'); // doesn't work as well

    }
  </script>
  <paper-button on-click="changeName">Change name</paper-button>

  <template id="repeater" is="dom-repeat" items='[{"name": "Foo", {"name": "Bar"}]'>
    <p>{{item.name}}</p>
  </template>
</template>

Upvotes: 0

Views: 199

Answers (1)

SG_
SG_

Reputation: 1336

Use 'items.0.name' instead of 'items#0.name' in the repeater.set(), and there is { mismatch in the predefined items array of #repeater. Here is a working demo.

<html>  
<head>

  <title>Template me</title>
  
  <script src="https://rawgit.com/webcomponents/webcomponentsjs/master/webcomponents.js"></script>
  
  <base href="https://cdn.rawgit.com/download/polymer-cdn/1.0.1/lib/">
  <link rel="import" href="polymer/polymer.html">  
  <link rel="import" href="paper-button/paper-button.html">  

  
</head>
<body class="fullbleed">

<template id="bind" is="dom-bind">
  <script>
    bind.changeName = function() {
      var repeater = document.querySelector('#repeater');
      //repeater.items[0].name = 'New Name' //doesn't work
      repeater.set('items.0.name', 'Another New Name'); //<==== Now it works ===

    }
  </script>
  <paper-button on-click="changeName">Change name</paper-button>

  <template id="repeater" is="dom-repeat" items='[{"name": "Foo"}, {"name": "Bar"}]'>
    <p>{{item.name}}</p>
  </template>
</template>


</body>
</html>

Upvotes: 1

Related Questions