[英]How can I listen to a RactiveJS custom component?
我有一個使用Ractive
定制組件的HTML
文件(我們稱它為TreeUser.html
)(在我的示例中,我們稱其為Tree)。 TreeUser使用此樹的方式如下:
Tree.js
...
var Tree = Ractive.extend({
template : Tree.html,
onrender : function() {
select : function(event) {
this.set("selected", event.context);
this.fire("selected", event.context)
}
})
});
return Tree;
})
TreeUser.html
<Tree>
....
</Tree>
TreeUser.js
var TreeUser = Ractive.extend({
...
components : {
Tree : Tree
},
onrender : function() {
// Here, I'd like to observe to Tree's fire. This does not work:
this.components.Tree.prototype.observe("selected", function(item){
// Do something
})
},
return TreeUser
這是我想做的事情:作為用戶,當在樹上完成選擇(因此調用了“選擇”功能)時,我希望TreeUser觀察事件並進行一些處理。 事實是我無法獲得樹的事件。
更一般而言,我希望能夠觀察使用過的組件觸發事件。 Ractive有可能嗎? 如果沒有,是否有任何解決方法?
我簡化了我的例子。 考慮除此事件觀察之外的所有方法。
編輯 :當我說:“它不起作用”時,我的意思是我收到了一個JavaScript錯誤: panel.components.Tree.observe is undefined
但是在調試器的控制台中, panel.components.Tree.prototype.observe
打印該函數的代碼。
您必須找到已創建的組件的tree
實例,然后對其進行調用。 (btw onrender
可以工作,但是IMO使用oninit
更有意義)
onrender : function() {
// use whatever tag alias you declared to "find" the component
this.findComponent('Tree').observe("selected", function(item){
// Do something
})
},
但是,您實際上並不需要觀察者! 父級可以使用與事件前綴相同的標簽別名直接訂閱組件事件:
oninit: function() {
this.on('Tree.selected', function(item){
// will fire when component fires selected event!
})
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.