javascript - polymer : Watch the changed Property from outside of an Component

标签 javascript html polymer web-component

我有 Polymer Webcomponent。

我现在的问题是,在组件之外,我对 DataBinding 场景使用了 knockout。现在我想创建自己的 Knockout 绑定(bind)类型,它能够将双向绑定(bind)与 Poylmer 对象一起使用。为此,我需要从组件外部订阅 Property 观察器。这可能吗?何时,如何?

最佳答案

是的,当 Polymer 属性有 notify: true 时,可以订阅属性更改通知.

Property change notification events (notify)

When a property is set to notify: true, an event is fired whenever the property value changes. The event name is:

_property-name_-changed

Where property-name is the dash-case version of the property name. For example, a change to this.firstName fires first-name-changed.

These events are used by the two-way data binding system. External scripts can also listen for events (such as first-name-changed) directly using addEventListener.

For more on property change notifications and the data system, see Data flow.

所以,如果您想订阅 <x-foo>.bar在外部与 Knockout 互操作,您可以使用 addEventListener()对于 bar-changed事件:

var foo = document.querySelector('x-foo');
foo.addEventListener('bar-changed', function(e) {
  console.log('new bar:', e.detail.value);
});

HTMLImports.whenReady(() => {
  Polymer({
    is: 'x-foo',
    properties : {
      bar: {
        type: String,
        value: 'Hello world!',
        notify: true
      }
    }
  });
});
<head>
  <base href="https://polygit.org/polymer+1.11.3/webcomponents+webcomponents+:v0/components/">
  <script src="webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="polymer/polymer.html">
</head>
<body>
  <x-foo></x-foo>
  <script>
    window.addEventListener('WebComponentsReady', function() {
      var foo = document.querySelector('x-foo');
      foo.addEventListener('bar-changed', function(e) {
        console.log('new bar:', e.detail.value);
      });
      
      foo.bar = 'hey';
      foo.bar = 'there!';
    });
  </script>

  <dom-module id="x-foo">
    <template>[[bar]]</template>
  </dom-module>
</body>

codepen

关于javascript - polymer : Watch the changed Property from outside of an Component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290951/

相关文章:

javascript - 将 google sheet 的副本复制到 google drive 文件夹中

Javascript:onkeyup 与 onsubmit 相处不来

javascript - dataTables JS Plugin响应宽度溢出设置div宽度

javascript - 没有背景图像的视差 div

unit-testing - Selenium 服务器未启动。另一个 Selenium 进程可能已经在运行,或者您的 java 版本可能已过时

javascript - 如何让 Ajax 表单提交在 ASP.net MVC 中工作?

javascript - 如何使用 selenium 在 Python 中刷新已有的网页?

HTML/CSS <div> 不会低于另一个

javascript - 将 jQuery 代码转换为 Polymer?

polymer - Firefox 的 Web Component Tester 中的所有测试均失败