Events communicate user interactions from the view layer to the logical layer for processing.
-
Events enable communication between the view layer and the logical layer.
-
Events pass user actions to the logical layer for processing.
-
Bind events to components. When triggered, the corresponding event handler at the logical layer runs.
-
Event objects carry extra information such as
id,dataset, andtouches.
Usage
To bind an event handler such as onTap to a component, define the handler in the Page object of the .js file.
<view id="tapTest" data-hi="Alipay" onTap="tapName">
<view id="tapTestInner" data-hi="AlipayInner">
Click me!
</view>
</view>
Define the event handler tapName in the Page object, with the event object as the parameter.
Page({
tapName(event) {
console.log(event);
},
});
The console outputs the following event object:
{
"type": "tap",
"timeStamp": 1550561469952,
"target": {
"id": "tapTestInner",
"dataset": {
"hi": "Alipay"
},
"targetDataset": {
"hi": "AlipayInner"
}
},
"currentTarget": {
"id": "tapTest",
"dataset": {
"hi": "Alipay"
}
}
}
Event availability depends on component support. Check each component's documentation for supported events.
Event types
Events fall into two types:
-
Bubbling event: Prefixed with
on. When triggered, the event propagates up to the parent node. -
Non-bubbling event: Prefixed with
catch. When triggered, the event does not propagate to the parent node.
Event binding syntax consists of a key and a value, similar to component attributes.
-
Key:
onorcatchfollowed by the event type, such asonTaporcatchTap. -
Value: the function name defined in the Page object. An error occurs if the function does not exist.
<view id="outter" onTap="handleTap1">
view1
<view id="middle" catchTap="handleTap2">
view2
<view id="inner" onTap="handleTap3">
view3
</view>
</view>
</view>
In the preceding example, tapping view3 triggers handleTap3 and handleTap2, because the tap event bubbles up to view2, which uses catchTap to stop further propagation. Tapping view2 triggers handleTap2. Tapping view1 triggers handleTap1.
The following table lists all bubbling event types.
|
Type |
Trigger condition |
|
touchStart |
Touch starts |
|
touchMove |
Finger moves after touch |
|
touchEnd |
Touch ends |
|
touchCancel |
Touch interrupted by an incoming call or pop-up |
|
tap |
Quick tap and release |
|
longTap |
Tap and hold for more than 500 ms |