Event Listening and Emitting

    Listen to events can be registered by the interface this.node.on(). The methods are as follows:

    1. // This event listener is triggered every time and needs to be unregistered manually.
    2. eventTarget.on(type, func, target?);

    The is the event registration string. func is the callback to listen to when the event is executed. And target is the event receive object. If target is not set, then this in the callback refers to the object that is currently executing the callback.

    The event listener interface on can pass to the third parameter target to bind the caller of the response function. Calling the following two methods would have the same effect:

    We can shut the corresponding event listener using off when we don’t care about a certain event anymore.

    The off method can be used in two ways

    1. eventTarget.off(type);
    2. eventTarget.off(type, func, target);

    One thing to note is that the parameter of off must be in one-to-one correspondence with the parameter of on in order to cancel it.

    Example:

    1. // At most 5 args could be emit.
    2. eventTarget.emit(type, ...args);

    When emitting events, we can pass our event parameters starting with the second argument of the emit function. Also, the corresponding event parameters can be fetched in the callback registered in on.

    Note: only up to 5 event parameters can be passed here for the performance of the underlying event distribution. Therefore, care should be taken to control the number of parameters passed when passing a parameter.

    Above are the general rules for listening to and emitting events. Cocos Creator has some built-in system events. Please refer to the following documents: