# event

# What is an event?

  • Events are the way the view layer communicates with the logic layer.
  • Events can feed the user's behavior back to the logic layer for processing.
  • An event can be bound to a component, and when a trigger event is reached, the corresponding event handling function in the logic layer is executed.
  • Event objects can carry additional information such as id, dataset, touches.

# How events are used

  • Bind an event handling function to the component.

For examplebindtap, when 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.4Starts. Support is provided for binding events using a WXS function. The WXS function accepts 2 parameters. The first is event, adding theevent.instanceobject on top of the original event. The second parameter is [[TAG-1- END]]ownerInstance,Likeevent.instanceis 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>
**注:绑定的WXS函数必须用{{}}括起来**

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

The ownerInstancecontains some methods for setting the style and class of the component. For details about the methods included and why you should respond to events with a WXS function, click to see the details .

# Details of the incident

# Classification of events

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

  1. Bubble event: When an event on a component is triggered, the event is passed to the parent node.
  2. Non-bubbling event: 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 conditions Minimum version
touchstart The finger touch action begins
touchmove The finger moves after touch
touchcancel Finger touch actions are interrupted, such as call reminders, window clicks
touchend The finger touch action ends
tap Leave immediately after touching your finger.
longpress After the finger touch, more than 350 ms before leaving, if the event callback function is specified and this 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 triggered after the WXSS transition or the wx.createAnimation animation
animationstart Will be triggered at the start of a WXSS animation
animationiteration Is triggered at the end of an iteration of a WXSS animation
animationend Will trigger when a WXSS animation is finished
touchforcechange On iPhone devices that support 3D Touch, retiming will trigger 1.9.90

Note: In addition to the above table, other component custom events are non-bubble events without special declarations, such as form 'ssubmitevent, input ''sinput]] event. scroll-view ofscrollevents, (see the individual components for details)

# Normal event binding

Event bindings are written in a way similar to the properties of a component, such as:

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

If the user clicks on this view, thehandleTapof the page is called.

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

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

At this point, thethis.data.handlerNameMust be a character string specifying the name of the event handler; If it is an empty character string, the binding is invalidated (you can use this feature to temporarily disable some events).

Since the base library version {% version ('1.5.0') %}, in most components and custom components,bindcan be followed by an apostrophe with the same meaning as [[]]bind:tap。This support is available in all components starting with the base library version {% version ('2.8.1')%}.

# Bind and stop the event from bubbling

In addition tobind,catchto bind events.Unlikebind,catchprevents events from bubbling up.

For example, in the following example, clicking on the inner view will callhandleTap3andhandleTap2(Because the tap event bubbles to the middle view, and the middle view prevents the tap event from bubbling and is no longer passed to the parent node), clicking on the middle view triggershandleTap2, clicking the 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

Since the base library version {% version ('2.8.2')%},In addition tobindandcatch, you can usemut-bindto bind events.After amut-bindis triggered, if the event bubbles to other nodes, themut-bind on other nodesbinding functions are not triggered, butbindbound functions andcatchbonds are still triggered.

In other words, allmut-bindare "mutually exclusive" and only one of the binding functions is triggered.At the same time, it has no effect onbindandcatch.

For example, in the following example, clicking on the inner view will callhandleTap3andhandleTap2,Clicking on the middle view will callhandleTap2andhandleTap1.

<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 incident

Since the base library version {% version ('1.5.0')%}, touch class events support the capture phase.The capture phase is located before the bubbling phase, and in the capture stages, events arrive at the nodes in exactly the opposite order of the bubbly phase.When you need to listen for events in the capture phase, you can usecapture-bind,capture-catchThe latter would interrupt the capture phase and cancel the bubbling phase.

In the following code, clicking on innerview will callhandleTap2handleTap4handleTap3handleTap1

<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 change the firstcapture-bindin the above code tocapture-catch,Will trigger onlyhandleTap2.

<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 specifically specified, when a component triggers an event, the processing function that binds the event in the logic layer receives an event object.

BaseEvent Base Event Object Property List:

attribute type Introductions Base library version
type String Type of event
timeStamp Integer Time stamp when the event is generated
target Object A collection of some property values of the component that triggers the event
currentTarget Object A collection of some attribute values of the current component
mark Object Event flagging data 2.7.1

CustomEvent custom event object property list (inheriting BaseEvent):

attribute type Introductions
detail Object Additional information

TouchEvent Touch Event object property list (inheriting BaseEvent):

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

Special Events: Touch events in canvas cannot bubble up, so there is no currentTarget.

# type

Represents the type of event.

# timeStamp

The page opens to the number of milliseconds that have passed to trigger the event.

# target

The source component that triggers the event.

attribute type Introductions
id String The id of the event source component
dataset Object A collection of custom attributes on the event source component that start withdata-

# currentTarget

The current component bound by the event.

attribute type Introductions
id String Id of the current component
dataset Object A collection of custom properties on the current component that start withdata-

Note: target and currentTarget can be referred to in the previous example. When clicking on innerview, the event objects received byhandleTap3target and current Target are inner, while the event Objects received by thehandletap2target is inner and the currentTarget is middle.

# dataset

You can attach some custom data to a component node. In this way, these custom node data can be obtained during an event for the logical processing of the event.

In WXML, these custom data start withdata-, and multiple words are connected by the hyphen-.In this type of writing, the hyphen type is converted to the hump type, and the uppercase character is automatically converted to a lowercase character. Examples include:

  • Data-element-type, eventually rendered asevent.currentTarget.dataset.elementType;
  • Data-elementType, eventually rendered asevent.currentTarget.dataset.elementtype.

Examples:

<view data-alpha-beta="1" data-alphaBeta="2" bindtap="bindViewTap"> DataSet Test </view>
Page({
  bindViewTap:function(event){
    event.currentTarget.dataset.alphaBeta === 1 // - 会转为驼峰写法
    event.currentTarget.dataset.alphabeta === 2 // 大写会转为小写
  }
})

# mark

Above base library version {% version ('2.7.1')%}, you can use themarkto identify the target node for a specific trigger event.In addition, themarkcan be used to carry some custom data (similar todataset)。

When an event fires, allmarkson the event bubble path are merged and returned to the event callback function.(Even if the event is not a bubbling event,mark.)

Code example:

Preview with Developer Tool

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

In the above WXML, if the button is clicked, it triggersbindViewTapandbindButtonTapTwo events, theevent.markthat the event carries, will contain bothmyMarkandanotherMark.

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

MarkanddatasetVery similar, but the main difference is thatmarkcontains allmark:attribute values from the node that triggered the event to the root node;Thedatasetcontains only one node'sdata-attribute value.

Detailed Note:

  • If there is amarkof the same name, the`mark [[TA.G-1-END]] of the parent node will be overridden by the node.
  • When receiving an event in a custom component,markdoes not contain themark
  • Unlikedataset, the node'smarkdoes not perform hyphens and case conversions.

# touches

Touches are an array, with each element a Touch object (the touches carried in the canvas touch event are the CanvasTouch array). Indicates a touch point currently stuck on the screen.

# TouchObject

attribute type Introductions
identifier Number The identifier of the touch point
pageX, pageY Number Distance from the upper-left corner of the document, where the origin is, the X axis horizontally and 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 Notes
identifier Number The identifier of the touch point
x, y Number The distance from the upper left corner of the canvas, the upper left corner of the canvas is the origin, the horizontal is the X axis, the vertical is the Y axis

# changedTouches

ChangedTouches data format with a touch. 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

Custom events carry data, such as a submit event for a form component that carries user input, and a media error event that carries error information, as described in the definition of each event in the component definition.

Click the event'sdetailwith x, y and pageX, and pageY represents the distance from the upper-left corner of the document.