tomalec
tomalec

Reputation: 900

How to attach propery-changed event to Polymer's dom-bind?

I'm trying to make Polymer's two-way data binding work with my native custom elements within auto-binding dom-bind. I follow the docs which says:

When using a Polymer element with other elements or frameworks, you can manually attach an on-property-changed listener to an element to be notified of property changes, and take the necessary actions based on the new value. So I created an element, and attached binding to it:

I tried attaching to event's triggered directly to the elements: Two-way data binding through property-changed does not work for dom-bind but it does not work, so now, I try to add listeners to dom-bind itself, which also seems to be broken:

  <template is="dom-bind" id="t">
    Let's try to listen to changes to <span>{{myobj}}</span> or <span>{{myobj.smth}}</span>
  </template>
    <script>
      var domBind = document.querySelector('#t');
      domBind.myobj = {smth: "myobj.smth"}
      // Another attempt to make Polymer binding work..
      domBind.addEventListener('myobj-changed', function() {
        alert("yey! myobj-changed works!")
      });
      // trigger changes in Polymer way
      domBind.set("myobj",{smth:"myobj.smthNew"});
      domBind.set("myobj.smth","myobj.smthComplatelyNew");
    </script>

Live example at http://jsbin.com/qubuku/edit?html,output

So it seems that the event is not triggered at all.

Upvotes: 1

Views: 2074

Answers (1)

hotforfeature
hotforfeature

Reputation: 2588

You're not giving Polymer enough time to load before you're triggering the property changes, that's what the dom-change event is for. Try this:

<template is="dom-bind" id="t">
  Let's try to listen to changes to <span>{{myobj}}</span> or <span>{{myobj.smth}}</span>
</template>
<script>
  var domBind = document.querySelector('#t');
  domBind.myobj = {smth: "myobj.smth"};
  domBind.addEventListener('myobj-changed', function() {
    alert("yey! myobj-changed works!")
  });

  document.addEventListener('dom-change', function() {
    domBind.set("myobj",{smth:"myobj.smthNew"}); // This won't trigger the event
    domBind.set("myobj.smth","myobj.smthComplatelyNew"); // This will trigger it
  });
</script>

Upvotes: 4

Related Questions