This Stack Overflow answer建议使用 <iron-signals>
将事件沿 DOM 树向下广播到自定义元素。
下面,我问一个不同的问题。
问题
How do I:
- pass an event down to a direct child node (custom element)
- from a parent (custom element)
- without using
<iron-signals>
?
代码
这是我到目前为止所拥有的。但它不起作用。
父元素.html
<dom-module id="parenet-element">
<template is="dom-bind">
<child-element></child-element>
<paper-button on-tap="_handleTap"></paper-button>
</template>
</dom-module>
<script>
(function(){
Polymer({
is: 'parenet-element',
_handleTap: function() {
this.fire("my-event");
}
});
})();
</script>
子元素.html<dom-module id="child-element">
...
</dom-module>
<script>
(function(){
Polymer({
is: 'child-element',
listeners: {
"my-event": "foo"
},
foo: function(){
// Do stuff
}
});
})();
</script>
最佳答案
你绝对可以。没有 iron-signals
你有三个选择(我目前知道):
document
触发该事件(但我认为这很糟糕)这是一个例子
<!doctype html>
<html>
<head>
<base href="http://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
</head>
<body>
<dom-module id="parent-element">
<template>
<child-element></child-element>
<button id="btn" on-tap="_fireParentEvent1">Fire 1!</button>
<button id="btn" on-tap="_fireParentEvent2">Fire 2!</button>
<button id="btn" on-tap="_fireParentEvent3">Fire 3!</button>
</template>
</dom-module>
<dom-module id="child-element">
<template>
<style>
:host {
display: block;
}
</style>
<span id="changeMe">Message</span>
</template>
</dom-module>
<parent-element></parent-element>
<script>
(function registerElements() {
Polymer({
is: 'parent-element',
listeners: {
'event-two': '_attachToChild'
},
_attachToChild: function(e) {
// the parent makes the child fire an event
var childElement = Polymer.dom(this.root).querySelector('child-element');
childElement.fire('event-two', e.detail);
},
_fireParentEvent1: function(e) {
// the parent fires an event
this.fire('event-one', {
message: 'hello'
});
},
_fireParentEvent2: function(e) {
this.fire('event-two', {
message: 'goodbye'
});
},
_fireParentEvent3: function(e) {
// the parent fires an event
this.fire('event-three', {
message: 'game over'
});
}
});
Polymer({
is: 'child-element',
listeners: {
'event-two': '_handleEventTwo'
},
ready: function() {
var parent = this.parentNode;
// the child listens to the parent's event
parent.addEventListener('event-one', function(e) {
this.$.changeMe.innerHTML = e.detail.message;
}.bind(this));
// listen to the document level event (since events travel up)
// but this option is difficult to control
document.addEventListener('event-three', function(e) {
this.$.changeMe.innerHTML = e.detail.message;
}.bind(this));
},
_handleEventTwo: function(e) {
this.$.changeMe.innerHTML = e.detail.message;
}
});
})();
</script>
</body>
</html>
关于javascript - polymer 1.0 : How to pass an event to a child-node element without using <iron-signals>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32770534/