gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:44:30 25 4
gpt4 key购买 nike

我有 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com