Event Introduction

What is event?

  • Event is the way of communication from the view layer to logic layer.
  • The event feeds user behaviors back to logic layer for handling.
  • Event can be bound to component. When the trigger condition happens, the corresponding event handler is executed in the logic layer.
  • Event object can carry additional information, such as id, dataset and touches.

Usage

If you want to bind an event handler in a component, for example onTap, you need to define the onTap function in the Page object in the relative .js file.

copy
<view id="tapTest" data-hi="Mini Program" onTap="tapName">
  <view id="tapTestInner" data-hi="Mini Program Inner">
    Click me! 
  </view>
</view>

In the relative Page, tapName should be defined to handle the event, and the parameter of the function is event.

copy
Page({
  tapName(event) {
    console.log(event);
  },
});

The console output

copy
{
  "type": "tap",
  "timeStamp": 1550561469952,
  "target": {
    "id": "tapTestInner",
    "dataset": {
      "hi": "Mini Program"
    },
    "targetDataset": {
      "hi": "Mini Program Inner"
    }
  },
  "currentTarget": {
    "id": "tapTest",
    "dataset": {
      "hi": "Mini Program"
    }
  }
}

In the use of components (basic component, extended component and custom component), the events available in the component depends on the support of the component itself. The supported events are specified clearly in the document of the specific component.

Event Type

The events fall into bubbling events and non-bubbling events:

  1. Bubbling events: With on as the prefix, when the event of a component is triggered, the event is transferred to parent node.
  1. Non-bubbling events: With catch as the prefix, when the event of a component is triggered, the event is not transferred to parent node.

The event binding is written is the same as component attribute in form of key, value.

  • The key starts with on or catch, followed by event type, such as onTap and catchTap.
  • The value is a string corresponding to the name of function defined in the Page. Error is reported when no trigger event exists.
copy
<view id="outter" onTap="handleTap1">
 view1
 <view id="middle" catchTap="handleTap2">
   view2
   <view id="inner" onTap="handleTap3">
     view3
   </view>
 </view>
</view>

In the above codes, clicking view3 triggers handleTap3 and handleTap2 (because tap event bubbles to view2m while view2 prevents tap event bubbling and does not transfer to parent node). Clicking view2 triggers handleTap2; clicking view1 triggers handleTap1.

All bubbling events:

TypeTrigger condition
touchStartStart of touch action.
touchMoveMove after touch.
touchEndEnd of touch action.
touchCancelTouch action interrupted, such as incoming call and pop-up.
tapTouch and leave immediately.
longTapTouch and leave after 500ms.