Events of Egret 2D(7)

event handling mechanism

In Egret, the event model defines a standard set of methods for generating and processing event messages, so that objects in the program can interact with each other, communicate, and maintain their own state and corresponding changes.

Simply put, the data provider just emits the data object , as long as the data object is an instance of the egret.Event class or a subclass . Such data objects are called events . The sender of the data object is called the event dispatcher. At the same time, the object that accepts the event is called the event listener (Event listener).

Here is a simple example:

When we want to date a male (female) friend, there is usually a date initiator and a date. Then this invitation process is a typical event process.

The boyfriend is the event sender, and the invitation to a date is the event sent by the boyfriend. And the girlfriend is the event listener.

This event contains three main contents: the type of the event, the target of the event, and the relevant data of the event . The type of event is an invitation to a date , and the girlfriend will perform different tasks according to the event. For example, if the event is "invite a date," the girlfriend might perform, get dressed, and then go to the date. If the event is "hungry", then the girlfriend will perform grocery shopping and cooking.

The target of the event is the sender of the event . Without this information, the girlfriend would have no way of knowing who asked her out or who was hungry when she received the incident.

The data of the event is the information to be included in the event. In the above dating event, the event information may include the event, the location, and what to do. In the same way, in the event of "I'm hungry", the information to be included is what to eat, whether to eat at home or go out to eat, etc. Of course, there are also some events that do not contain information, such as "beating the back", as long as the event recipient receives this event, it can be executed directly.

Event execution flow

The event mechanism consists of 4 steps: register listeners, send events, listen for events, and remove listeners . These four steps are performed in order.

Register a listener , that is, specify which method of which object receives the event. In the dating example, we specify that the boyfriend sends the event and the girlfriend receives the event.

Events sent can only be listened to after a listener is registered. And the event sent must match the type of the listener event. After the event is sent, the listener cannot listen to the event.

Event class

The Event class is the base class for all event classes. When creating a custom event, the event should inherit from the Event class . At the same time the Event class also contains some events. These events are usually related to the display list, the state of the display object

When using the Event class, there are the following properties and methods to pay attention to:

  • The first is the three parameters in the constructor, type, bubbles and cancelable
  •  type specifies the type of event , in the "date" example, the type event type is "DATE". The event types we often use are "ADDED", "COMPLETE", etc. When customizing the event, the type type is specified by itself.
  • bubbles is to specify whether the event participates in the bubbling phase of the event flow. About the event flow, it will be introduced in the following subsections.
  • cancelable indicates whether the default action associated with the event can be canceled.
  • Another attribute that needs attention is target, which represents the target of the event, that is, the sender of the event. Some other methods are related to event flow, which will be described in detail later.

event listener

The event listener is the handler of the event, responsible for receiving the information carried by the event, and executing specific code after receiving the event.

In Egret, the event listener must be a function. The sender of the event must be an instance of the egret.EventDispatcher class or a subclass . Only event senders can listen to events, and listeners can be registered.

Listening to events is divided into two parts . The first is to establish a listener . The listener can be an independent function or a method of an object. The second step is to register the listener , using the event sender's addEventListener() to assign the corresponding event to the listener.

Create (build) a listener

The listener must be a function, it can be a standalone function or an instance method. The listener must have a parameter, and this parameter must be an instance of the Event class instance or its subclass, and the return value of the listener must be empty (void) . The sample code is as follows

listenerName(evt:Event):void {...}

Note: Generally defined in the event listener, that is, the receiver object of the event.

public getDate(evt:DateEvent)
    {
        console.log("得到了" + evt.target.name + "的邀请!" );
        console.log("事件侦听者处理事件");
    }

Registering and removing listeners

Only the sender of the event can register the listener, and the sender of the event must be an instance of the EventDispatcher class or its subclasses. The same is true for removing listeners. Usually, registering listeners and removing listeners are paired .

Register the listener:

事件发送者.addEventListener(事件类型, 侦听器, this);

The definition of the registered listener function:

public addEventListener(type:string, listener:Function, thisObject:any, useCapture:boolean = false, priority:number = 0)

  • type : Event type, required.
  • listener : The listener used to handle the event, required.
  • thisObject : scope, required, usually fill in this. Because TypeScript and JavaScript have different this scopes, their this points will also be different. If you do not fill in this, then the compiled code will have an error. Regarding this question, you can learn the prototype chain in JavaScript.
  • useCapture : Determines whether the listener runs in the capture phase or the bubbling phase, optional. When set to true, the listener only handles events during the capture phase, not during the bubbling phase. Set to false, the listener will only process events during the bubbling phase.
  • priority : The priority of the event listener, optional. The priority is specified by a signed integer. The higher the number, the higher the priority. All listeners with priority n are processed before listeners with priority n -1. If two or more listeners share the same priority, they are processed in the order in which they were added. The default priority is 0.

Remove the listener:

事件发送者.removeEventListener(事件类型, 侦听器, this);

detection listener

If you need to detect in your logic whether an event sender has registered a listener, there are two methods you can use. One is hasEventListener and the other is willTrigger . The two methods have the same effect, and both determine whether an event sender has registered a certain type of event.

Returns true if the event type has been registered, false if it has not been registered .

事件发送者.hasEventListener(事件类型);

Start switch for TouchEvent

TouchEvent's enable switch touchEnabled Specifies whether this object receives touch or other user input. The default value is false, and the instance will not receive any touch events (or other user input events). If touchEnabled is set to true , the display object instance will receive touch events or other user input events. To change the touchEnabled behavior of all children of a display object , use DisplayObjectContainer.touchChildren

The actual use process, if some display objects need to listen to TouchEvent, please open it first:

显示对象实例.touchEnabled = true;

A simple understanding is to allow the display object to respond to gesture events

Custom event (dating example)

fulfillment dating

Event class :


//自定义事件类
//注意事件要继承egret.Event类
class DateEvent extends egret.Event{
	//注意构造函数接受三个参数                
	public constructor(type:string, bubbles:boolean, cancelable:boolean) {
		//注意super中的参数。
		//事件类接受三个参数后传给super调用父构造函数
		super(type,bubbles,cancelable);
	}

    //定义静态事件类型type,为什么要静态?给发送者直接访问并传入作为本类的构造函数的参数type
	public static YUEHUI:string="约会";//事件type为约会
	//定义约会地点
	public address:string;
	//定义约会时间
	public time:string;

}

Event Sender---Boyfriend in Dating :

//男朋友类--事件发送者
class Boy extends egret.Sprite{
	public constructor() {
		super();
	}
	public sendEvent(){
		//实例化约会事件对象
		//其中DateEvent.YUEHUI是访问事件类中的静态成员变量YUEHUI作为事件的类型type
		let dataEvent:DateEvent=new DateEvent(DateEvent.YUEHUI,false,false);
		//添加事件的数据---约会地点
		dataEvent.address="厦门鼓浪屿";
		//添加事件的数据--约会时间
		dataEvent.time="晚上7点";
		//发送要求事件
		this.dispatchEvent(dataEvent);
	}
}

Event Receiver--Girlfriend Class

Processing after receiving event information

//女朋友类--事件接受者对象---事件侦听者
class Girl extends egret.Sprite{
	public constructor() {
		super();
	}

	//创建侦听器
	public goYueHui(evt:Event):void{
		/*
			这里as xxx和<xx>是ts的类型断言。这里如果不这样写会编译报错,其实代码没有错的。
			这是因为ts是静态语言。简单就是一开始evt并没有定义一些属性,使我们动态设置的。

			as 语法和<>尖括号语法的作用是一样的
			
		*/
		console.log("接受了"+(evt as any).target.name+"的邀请");
		console.log("约会地点:"+(evt as any).address);	
		console.log("约会时间:"+(<any>evt).time);	
	}
}

call trigger send event

//实例化男朋友
            let boy:Boy=new Boy();
            boy.name="男朋友";
            //实例化女朋友
            let girl:Girl=new Girl();
            girl.name="女朋友";
            //注册侦听器
            boy.addEventListener(DateEvent.YUEHUI,girl.goYueHui,girl);//参数为事件类型,处理事件的侦听器,作用域
            //男朋友发送要求
            boy.sendEvent();
            //约会邀请完成后,移除侦听器
            boy.removeEventListener(DateEvent.YUEHUI,girl.goYueHui,girl);

Minimalist custom events

The following demonstrates a custom event, which directly new the parent class (Event) of an event, and the event does not require event information. Trigger sending events directly based on conditions. "jumpGame" is simply understood as the time type (and the event name can also be understood)

Event sender:

let event=new egret.Event("jumpGame",false,false);                                                                                                                                                                                                                                                
//点击事件
btnWrap.addEventListener(egret.TouchEvent.TOUCH_TAP,()=>{
	//发送事件
	this.dispatchEvent(event);
},this);

Event receivers and listeners:

  this.game.addEventListener("jumpGame",()=>{
         //处理事件
  },this);

touch event

For mobile games, touch events are the most common type of user interaction event. Egret sets a special touch event class egret.TouchEvent for touch events

The types of events it contains mainly include:

  • TOUCH_BEGIN : Fired when the user touches a touch-enabled device for the first time (for example, touching a mobile phone or tablet with a touchscreen with a finger)
  • TOUCH_CANCEL : Fired when a touch is canceled due to an event
  • TOUCH_END : Triggered when the user removes contact with a touch-enabled device (for example, lifts a finger from a mobile phone or tablet equipped with a touchscreen)
  • TOUCH_MOVE : Fires when the user touches the device and moves, and fires continuously until the touchpoint is removed
  • TOUCH_TAP : Fired when the user lifts the touch point on the touch device on the same DisplayObject instance that started the touch (equivalent to a tap event)

When using touch events in Egret, you need to turn on the touch event switch of the display object, that is, set the touchEnabled property of the display object to true

   //设置显示对象可以相应触摸事件
        spr1.touchEnabled = true;
        //注册事件
        spr1.addEventListener( egret.TouchEvent.TOUCH_TAP, this.onTouch, this );
...........


    private onTouch( evt:egret.TouchEvent )
    {
       ...........
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324788508&siteId=291194637