简体   繁体   中英

How can I listen to a RactiveJS custom component?

I have a HTML file (let's call it TreeUser.html ) using a Ractive custom component (let's call it Tree in my example). This Tree is used by TreeUser as follows:

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

Here is what I'd like to do: As a user, when a selection is done on the tree (and so the function "select" is called), I'd like my TreeUser to observe the events and do some treatments. The fact is I am unable to get the Tree's events.

More generically, I'd like to be able to observe used components fired events. Is it possible with Ractive? If not, is there any workaround?

I have simplified my example. Consider everything works except this events observation.

EDIT : When I say: "it does not work", I mean I get a javascript error: panel.components.Tree.observe is undefined

But in the console of my debugger, panel.components.Tree.prototype.observe prints the code of the function.

You have to find the tree instance of the component that was created and call observe on that. (btw onrender works, but IMO it makes more sense to use oninit )

onrender : function() {
    // use whatever tag alias you declared to "find" the component 
    this.findComponent('Tree').observe("selected", function(item){
        // Do something
    })
}, 

But, you don't really need an observer! The parent can directly subscribe to the component event using the same tag alias as an event prefix:

oninit: function() {
    this.on('Tree.selected', function(item){
        // will fire when component fires selected event!
    })
}, 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM