Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple event handlers to same event in React.js

All:

I wonder if it is possible that binding multiple event handlers to same event?

For example:

var LikeToggleButton = React.createClass({
    render: function(){
        (function toggle(){
            this.setState({liked:!like});
        }).bind(this);
        return (
            <div onClick={toggle}>TOGGLE LIKE</div>  
        );
    }
});

Until this point everything seems normal, but I want to add another feature to that button, which is decide by other option:

For example, I have another switch component(could be anything like checkbox or radio button etc.) called "count toggle", which when enabled, the LikeToggleButton's button will be added another onClick handler which is start counting times of button clicked, I know it could be predesignd into the toggle function, but I just wonder if there is a way to append this part to onClick handler?

Thanks

like image 724
Kuan Avatar asked Oct 28 '15 18:10

Kuan


People also ask

Can we have more than one event handler method for same event?

You can assign as many handlers as you want to an event using addEventListener(). addEventListener() works in any web browser that supports DOM Level 2.

Can you add two event listeners to the same button?

Can you have more than one event listener? We can add multiple event listeners for different events on the same element. One will not replace or overwrite another. In the example above we add two extra events to the 'button' element, mouseover and mouseout.

Can multiple listeners be attached to an event?

An event listener is added to an element on the page, such as a button. The event listener will invoke a specified function when the event triggers. Javascript supports multiple functions on a single event, as well as multiple event listeners for a single element.


1 Answers

If you want to have multiple callbacks executed when onClick is triggered, you can have them passed from outside, so you'll have access to them in the props object. Then execute them all (note: code not tested):

var LikeToggleButton = React.createClass({

    toggle: function() {
        this.setState({liked:!like});
    },

    handleClick: function(e) {
        e.preventDefault();
        this.toggle();
        for (var i=0, l<this.props.callbacks.length; i<l; i++) {
           this.props.callbacks[i].call();
        }
    },

    render: function() {            
        return (
            <div onClick={this.handleClick}>TOGGLE LIKE</div>  
        );
    }
});

BUT, if you want to have components connected between them, you should not do that by calling methods inside handlers. Instead you should use an architectural pattern, where Flux is the obvious choice (but there are lots more).

Take a look to Flux, and here you have more choices.

like image 123
gontrollez Avatar answered Oct 11 '22 03:10

gontrollez