Javascript 使用来自父函数的事件在子元素中创建聚合触发器函数
我有一个元素,其子元素充当按钮。当我在父元素的输入框中按Enter键时,我想触发子元素的runNavigation方法。在父元素向子元素触发事件的情况下,创建自定义触发器的最佳方法是什么 我已尝试在我的子元素中创建EventListener:Javascript 使用来自父函数的事件在子元素中创建聚合触发器函数,javascript,html,dom,polymer,polymer-1.0,Javascript,Html,Dom,Polymer,Polymer 1.0,我有一个元素,其子元素充当按钮。当我在父元素的输入框中按Enter键时,我想触发子元素的runNavigation方法。在父元素向子元素触发事件的情况下,创建自定义触发器的最佳方法是什么 我已尝试在我的子元素中创建EventListener: <...> <button type="button" class="btn btn-success" on-click="_runNavigation">{{result}}</button <...> Pol
<...>
<button type="button" class="btn btn-success" on-click="_runNavigation">{{result}}</button
<...>
Polymer({
is: 'search-button',
properties: {
searchQuery: {
type: String,
}
},
ready : function (){
document.addEventListener('fire', this._runNavigation);
},
navigate: function(url) {
var win = window.open(url, '_blank');
if (win != null) {
win.focus();
}
},
_runNavigation: function() {
var text = this.searchQuery;
this.navigate("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=" + text);
},
});
{{result}}如果您别无选择,只能从聚合元素中使用document.addEventListener
,则必须设置的上下文。_runNavigation
:
虽然这在您的示例中有效,但它会侦听整个文档上的fire
事件,因此,如果表单继承权限之外的任何其他元素触发了该事件,它将触发元素的处理程序,这可能是不需要的。例如:
<x-form></x-form> <!-- listens to all 'fire' events -->
<script>
setTimeout(function() {
// unrelated 'fire'
document.dispatchEvent(new Event('fire'));
}, 1000);
</script>
然后,在搜索按钮元素中,您将使用:
this.addEventListener('fire', this._runNavigation); // bind() not necessary here
请注意,在本演示中,fire
事件不会出现在文档中(事件处理程序中没有记录警告)
谢谢!我不知道fire call包含包含节点的功能@泰金,没问题:)
<x-form></x-form> <!-- listens to all 'fire' events -->
<script>
setTimeout(function() {
// unrelated 'fire'
document.dispatchEvent(new Event('fire'));
}, 1000);
</script>
this.fire('fire', { searchQuery: this.searchQuery }, { bubbles:false, node: this.$.searchButton });
this.addEventListener('fire', this._runNavigation); // bind() not necessary here