我有 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 tothis.firstName
firesfirst-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 usingaddEventListener
.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>
关于javascript - polymer : Watch the changed Property from outside of an Component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40290951/