# event

# What is an event?

  • Events are the communication between the visual layer and the logical layer.
  • Events feed back user behavior to the logical layer for processing.
  • Events can be bound to components, and when an event is triggered, the corresponding event handler in the logical layer is executed.
  • Event objects can carry additional information, such as id, dataset, touches。

# How events are used

  • Binding an event handler in a component.

Such asBindtapWhen the user clicks on the component, the corresponding event handler will be found in the Page corresponding to that page.

<view id="tapTest"  data-hi="Weixin"  bindtap="tapName" > Click me! </view>
  • Write the corresponding event handler in the corresponding Page definition, and the parameter is event.
Page({
  tapName: function(event) {
    console.log(event)
  }
})
  • You can see the log information roughly as follows:
{
  "type":"tap",
  "timeStamp":895,
  "target": {
    "id": "tapTest" 
    "dataset":  {
      "hi":"Weixin"
    }
  },
  "currentTarget":  {
    "id": "tapTest" 
    "dataset": {
      "hi":"Weixin"
    }
  },
  "detail": {
    "x":53,
    "y":14
  },
  "touches":[{
    "identifier": 0, 
    "pageX":53,
    "pageY":14,
    "clientX":53,
    "clientY":14
  }],
  "changedTouches":[{
    "identifier": 0, 
    "pageX":53,
    "pageY":14,
    "clientX":53,
    "clientY":14
  }]
}

# Using WXS functions to respond to events

Start from base library version 2.4.4. Please remaining backward compatible.

From the base library version2.4.4Start, support the use of WXS function to bind events, WXS function accepts two parameters, the first is the event, in the original event on the basis of addingevent.instanceObject, the second argument isownerInstance, andevent.instanceThe same is aComponentDescriptorObject. Specific uses are as follows:

  • WXS functions that bind and register event handling in components.
<wxs module="wxs"  src="./test.wxs"></wxs>
<view id="tapTest"  data-hi="Weixin"  bindtap="[wxs.tapName}}" > Click me! </view>
**Note: Bound WXS functions must be enclosed by {{}}**

  • The test.wxs file implements the tapName function
function tap (event, ownerInstance) {
  console.log('tap Weixin',  JSON.stringify(event))
}
module.exports = {
  tapName: tap 
}

ownerInstanceContains some methods, you can set the style and class of the component, the specific methods included and why you should use the WXS function to respond to events, pleaseClick for details

# Details of the incident

# Event classification

Events are divided into bubble events and non-bubble events:

  1. Bubbling Event: When an event on a component is triggered, the event is passed to the parent node.
  2. Non-bubbling events: When an event on a component is triggered, the event is not passed to the parent node.

List of bubbling events for WXML:

type Trigger condition Minimum version
Touchstart Finger touch action begins.
touchmove Move after finger touch
touchcancel Finger touch action is interrupted, such as call alert, pop-up window
touching Finger Touch Action End
tap Touch your finger and leave immediately.
longpress After the finger touch, more than 350 ms before leaving, if the event callback function is specified and the event is triggered, the tap event will not be triggered 1.5.0
Longtap After finger touch, more than 350 ms before leaving (recommended to use the longpress event instead)
transitionend Will be in WXSS transition or wx.createAnimation Triggered after the end of the animation
animationstart Will be in a WXSS animation Triggered at the start of the animation
animationiteration Will be in a WXSS animation Triggered at the end of an iteration
End of animation Will be in a WXSS animation Triggered when animation is complete
touchforcechange In support of 3D Touch of iPhone Equipment, the heavy time will trigger 1.9.90

Note: Component custom events other than those in the above table are non-bubbling events without special declarations, such as form ofsubmitEvents,input ofinputEvents,scroll-view ofscrollEvents,(See eachassembly)

# Ordinary Event Binding

Event binding is written similarly to the properties of a component, such as:

<view bindtap="handleTap" >
    Click here!
</view>

If the user clicks on this view , then the page's handleTap Will be called.

The event binding function can be a data binding, such as:

<view bindtap={{  handler  }}">
    Click here!
</view>

At this point, the page's this.data.handlerName Must be a character string specifying the name of the event handlerIf it is an empty character string, the binding is invalidated (you can use this feature to temporarily disable some events).

Self-base library version 1.5.0 In most components and custom components, bind Can be followed by a colon, the meaning of the same, such as bind:tap Base Library Version 2.8.1 Start providing this support in all components.

# Binding and Preventing Event Bubbles

except bind Outside, you can also use catch To bind events. and bind Different, catch Will stop the incident from bubbling up.

For example, in the example below, click Inner view Will call in turnhandleTap3andhandleTap2(Because the tap event will bubble up to middle View, and middle view Stopped it. tap Event bubbles and no longer passes to the parent node), Click middle view Will triggerhandleTap2, Click Outer view Will triggerhandleTap1

<view id="outer" bindtap="handleTap1" >
  Outer view
  <view id="middle" catchtap="handleTap2">
    middle view
    <view id="inner"  bindtap="handleTap3" >
      Inner view
    </view>
  </view>
</view>

# Mutually exclusive events binding

Self-base library version 2.8.2 From, except bind and catch Outside, you can also use mut-bind To bind events. One mut-bind After firing, if the event bubbles to other nodes, the mut-bind The binding function will not be triggered, but the bind Binding Functions and catch The binding function is still triggered.

In other words, all mut-bind Are "mutually exclusive," only one of the binding functions will be triggered. At the same time, it does not affect at all bind and catch Of the binding effect.

For example, in the example below, click Inner view Will call in turn handleTap3 and handleTap2 , Click middle view Will call handleTap2 and handleTap1

<view id="outer" mut-bind:tap="handleTap1" >
  Outer view
  <view id="middle" bindtap="handleTap2" >
    middle view
    <view id="inner"  mut-bind:tap="handleTap3" >
      Inner view
    </view>
  </view>
</view>

# The capture phase of the event

Self-base library version 1.5.0 Touch events support the capture phase. The capture phase precedes the bubble phase, and in the capture phase, events arrive at nodes in the opposite order to the bubble phase. When you need to listen for events during the capture phase, you can usecapture-bindcapture-catchKeyword, which interrupts the capture phase and cancels the bubble phase.

In the code below, click Inner view Will call in turnhandleTap2handleTap4handleTap3handleTap1

<view id="outer" bind:touchstart="handleTap1"  capture-bind:touchstart="handleTap2" >
  Outer view
  <view id="inner"  bind:touchstart="handleTap3"  capture-bind:touchstart="handleTap4" >
    Inner view
  </view>
</view>

If you add the first one in the above codecapture-bindto change intocapture-catch, will only be triggeredhandleTap2

<view id="outer" bind:touchstart="handleTap1"  capture-catch:touchstart="handleTap2">
  Outer view
  <view id="inner"  bind:touchstart="handleTap3"  capture-bind:touchstart="handleTap4" >
    Inner view
  </view>
</view>

# Event object

Unless otherwise specified, when a component fires an event, the handler to which the logical layer binds the event receives an event object.

BaseEvent List of Base Event Object Properties:

attribute type Introductions Base Library Version
type String Type of event
timeStamp Integer Timestamp when the event is generated
target Object A collection of property values for the component that triggers the event
currentTarget Object Some collection of property values for the current component
mark Object Event Tag Data 2.7.1

CustomEvent Custom Event Object Property List (inherited from BaseEvent):

attribute type Introductions
detail Object Additional information

TouchEvent Touch Event Object Property List (inherited BaseEvent):

attribute type Introductions
touches Array Touch events, an array of touch point information currently staying on the screen
changedTouches Array Touch events, an array of currently changing touch point information

Special Events: canvas The touch event in the currentTarget。

# type

Represents the type of event.

# timeStamp

The number of milliseconds elapsed since the page opened until the event triggered.

# target

The source component that triggers the event.

attribute type Introductions
id String The id of the event source component
dataset Object On the event source componentdata-A collection of custom properties at the beginning

# currentTarget

The current component of the event binding.

attribute type Introductions
id String Id of the current component
dataset Object On the current componentdata-A collection of custom properties at the beginning

Dxplaination: target and currentTarget You can refer to the example above, click Inner view When,handleTap3 Received Event Object target and currentTarget Both. Inner, and handleTap2 Received Event Object target Namely inner,currentTarget Namely middle。

# dataset

You can attach some custom data to the component node. In this way, these custom node data can be retrieved in the event for the logical handling of the event.

in WXML This custom data is defined in data- Beginning, multiple words are represented by a hyphen - Connection. In this way, the hyphen is converted to the camel hump, and the uppercase character is automatically converted to lowercase. Such as:

  • data-element-type , will eventually be presented as event.currentTarget.dataset.elementType
  • data-elementType , will eventually be presented as event.currentTarget.dataset.elementtype

Example:

<view data-alpha-beta="1" data-alphaBeta="2" bindtap="bindViewTap"> DataSet Test </view>
Page({
  bindViewTap:function(event){
    event.currentTarget.dataset.alphaBeta === 1 // - Will turn to the hump script.
    event.currentTarget.dataset.alphabeta === 2 // Uppercase will turn to lowercase
  }
})

# mark

In the base library version 2.7.1 Above, you can use mark To identify the specific triggering event target Node. In addition, mark Can also be used to host some custom data (similar to the dataset )。

When the event is triggered, the event bubble path for all the mark Will be merged and returned to the event callback function. (Even if the event is not a bubble event, it will mark 。)

Code example:

{% Minicode ('7LwTKvmi7woT') %}

<view mark:myMark="last" bindtap="bindViewTap">
  <button mark:anotherMark="leaf" bindtap="bindButtonTap" >Button</button>
</view>

In the above WXML If the button is clicked, it will trigger bindViewTap and bindButtonTap Two events. The event carries the event.mark Will contain myMark and anotherMark Two.

Page({
  bindViewTap: function(e) {
    e.mark.myMark === "last" // true
    e.mark.anotherMark === "leaf" // true
  }
})

mark and dataset Very similar. The main differences are: mark Will contain everything from the node that triggered the event to the root node mark: Attribute valueand dataset Containing only one node data- Property value.

Attention to detail:

  • If the same name exists mark , the parent node's mark Will quilt nodes covered.
  • When an event is received in a custom component, mark That does not contain nodes outside the custom component mark
  • Unlike dataset , Node's mark Does not do hyphens and case conversions.

# touches

touches Is an array, each element for a Touch Object (canvas The Touch Incident Carried touches yes CanvasTouch Array). Represents the touchpoint that is currently resting on the screen.

# Touch object

attribute type Introductions
identifier Number Identifier of the touch point
pageX, pageY Number Distance from the top-left corner of the document, which is the origin , for the X axis horizontally, for the Y axis vertically
clientX, clientY Number Distance from the upper left corner of the viewable area of the page (screen removed from the navigation bar), horizontal for X axis, vertical for Y axis

# CanvasTouch object

attribute type Introductions Special instructions
identifier Number Identifier of the touch point
x, y Number distance Canvas Distance from the upper left corner, Canvas The upper left corner of , for the X axis horizontally, for the Y axis vertically

# changedTouches

changedTouches Data format same as touches。 Indicates a change in touch points, such as a change from nothing (touchstart), a change in position (touchmove), a change from nothing (touchend, touchcancel).

# detail

Data carried by custom events, such as form component submission events that carry user input and media error events that carry error messages, seeassemblyDefinition of the individual events in the definition.

Click on the event'sdetail With x, y with pageX, pageY Represents the distance from the top-left corner of the document.