先捕获后冒泡,顺序相反,捕获从外到内,捕获到catch为止, 冒泡从里到外,冒泡到catch为止
事件分为冒泡事件和非冒泡事件:
bind
事件绑定不会阻止冒泡事件向上冒泡,catch
事件绑定可以阻止冒泡事件向上冒泡。事件绑定的写法同组件的属性,以 key、value 的形式。
bind
或catch
开头,然后跟上事件的类型,如bindtap
、catchtouchstart
。自基础库版本 1.5.0 起,在非原生组件中,bind
和catch
后可以紧跟一个冒号,其含义不变,如bind:tap
、catch:touchstart
。bind
事件绑定不会阻止冒泡事件向上冒泡,catch
事件绑定可以阻止冒泡事件向上冒泡。
如在下边这个例子中,
点击 inner view 会先后调用handleTap3
和handleTap2
(因为tap事件会冒泡到 middle view,而 middle view 阻止了 tap 事件冒泡,不再向父节点传递),
点击 middle view 会触发handleTap2
,
点击 outer view 会触发handleTap1
。
<view id="outer" bindtap="handleTap1"> outer view <view id="middle" catchtap="handleTap2"> middle view <view id="inner" bindtap="handleTap3"> inner view </view> </view></view>
target 触发事件的源组件。
currentTarget 事件绑定的当前组件。
说明: target 和 currentTarget 可以参考上例中,点击 inner view 时,
handleTap3
收到的事件对象 target 和 currentTarget 都是 inner,
而 handleTap2
收到的事件对象 target 就是 inner,currentTarget 就是 middle。
自基础库版本 1.5.0 起,触摸类事件支持捕获阶段。
1.捕获阶段位于冒泡阶段之前
2.且在捕获阶段中,事件到达节点的顺序与冒泡阶段恰好相反
3.需要在捕获阶段监听事件时,可以采用capture-bind
、capture-catch
关键字
4.后者(capture-catch)将中断捕获阶段和取消冒泡阶段
在下面的代码中,点击 inner view 会先后调用handleTap2
、handleTap4
、handleTap3
、handleTap1
。
<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>
如果将上面代码中的第一个capture-bind
改为capture-catch
,将只触发handleTap2
。
<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>
dataset
在组件中可以定义数据,这些数据将会通过事件传递给 SERVICE。书写方式:以data-
开头,多个单词由连字符-
链接,不能有大写(大写会自动转成小写)如data-element-type
,最终在 event.currentTarget.dataset 中会将连字符转成驼峰elementType
。
连字符之后的单词首字母大写,一个单词中的大写转为小写示例:
<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 // 大写会转为小写 }})
引用
WXML 提供两种文件引用方式import
和include
import 有作用域的概念,即只会 import 目标文件中定义的 template,而不会 import 目标文件 import 的 template。
如:C import B,B import A,在C中可以使用B定义的template
,在B中可以使用A定义的template
,但是C不能使用A定义的template
。
include
include
可以将目标文件除了 <template/>
<wxs/>
外的整个代码引入,相当于是拷贝到 include
位置
<!-- index.wxml --><include src="header.wxml"/><view> body </view><include src="footer.wxml"/>
<!-- header.wxml --><view> header </view>
<!-- footer.wxml --><view> footer </view>
联系客服