如何将有意改变的事件附加到Polymer的dom-bind?

时间:2015-09-14 19:27:54

标签: javascript data-binding polymer

我正在尝试使Polymer的双向数据绑定与自动绑定dom-bind中的本机自定义元素一起使用。我按照文档说:

  

当您将Polymer元素与其他元素或框架一起使用时   可以手动将属性更改后的侦听器附加到元素   收到有关财产变更的通知,并采取必要的行动   关于新的价值。所以我创建了一个元素,并附加了它的绑定:

我尝试将事件直接触发到元素:Two-way data binding through property-changed does not work for dom-bind 但它不起作用,所以现在,我尝试将监听器添加到dom-bind本身,这似乎也被打破了:

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

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

的实例

所以似乎事件根本没有被触发。

1 个答案:

答案 0 :(得分:3)

在您触发属性更改之前,您没有给予Polymer足够的时间加载,这是dom-change事件的用途。试试这个:

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