【发布时间】:2016-06-11 18:47:31
【问题描述】:
我有一个带有子元素的元素,它充当按钮。当我在父元素的输入框中按“Enter”时,我想触发子元素的 _runNavigation 方法。在父元素向子元素触发事件的情况下,创建自定义触发器的最佳方法是什么?
我尝试在我的子元素中创建一个 EventListener:
<...>
<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);
},
});
当文本框处于焦点时按下回车时触发事件:
<...>
<input id="input" type="text" value="{{searchQuery::input}}" on-keydown="checkForEnter" on-change="_inputChanged" class="form-control" placeholder="Search">
<...>
checkForEnter: function(e) {
// check if 'enter' was pressed
if (e.keyCode === 13) {
// enter pressed!
console.log("ENTER!");
this.fire('fire', {searchQuery: this.searchQuery});
}
}
虽然这将触发由子元素拾取的事件,但“this.navigate”将不会运行,因为“this”现在是文档。我尝试将事件侦听器更改为 this.addEventListener('fire', this._runNavigation); 将其添加到元素本身,但随后该元素未检测到来自父元素的触发器。
【问题讨论】:
标签: javascript html dom polymer polymer-1.0