我有一個具有充當按鈕的子元素的元素。當我在父元素的輸入框中按'Enter'時,我想觸發孩子的_runNavigation方法。在父項將事件觸發到子元素時創建自定義觸發器的最佳方法是什麼?使用來自父函數的事件的子元素中的聚合物觸發函數
我試圖在我的子元素創建的事件監聽:
<...>
<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); 將它添加到元素本身,但然後該元素不檢測父元素的觸發器。
謝謝!我不知道消防呼叫包含了包含節點的能力! – Tykin
@Tykin,沒問題:) – tony19