事件
事件是视图层到逻辑层的通讯方式
事件可以将用户的行为反馈到逻辑层进行处理
事件可以绑定在组件上,当达到触发事件,就会执行逻辑层中对应的事件处理函数
事件对象可以携带额外信息。(数据信息)
事件分类
事件分为冒泡事件和非冒泡事件。
冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。
非冒泡事件:当一个组件上的事件被触发后,该事件不会向父节点传递
事件绑定
事件绑定的写法同组件的属性,以key,value的形式
-- key 以bind或catch开头,然后跟上事件的类型 如:bindtap, catchtouchstart
-- value是一个字符串,需要在对应的Page中定义同名的函数,不然当触发事件的时候会报错
注意:bind
事件绑定不会阻止冒泡事件向上冒泡,catch
事件绑定可以阻止冒泡事件向上冒泡。
如下:
<view id="outter" bindtap="handleTap1">
outer view
<view id="middle" catchtap="handleTap2">
middle view
<view id="inner" bindtap="handleTap3">
inner view
</view>
</view>
</view>
上述结果:当点击inner view的时候会触发handleTap3和handleTap2.当点击middle view的时候只会触发hindleTap2 ,不会向上冒泡
事件对象
如无特殊说明,当组件触发事件时,逻辑层绑定该事件的处理函数会收到一个事件对象。
例子:(参考:https://www.w3cschool.cn/weixinapp/weixinapp-event.html)
.wxml
<view bindtap="example1"> type example </view>
<view bindtap="example2"> target example </view>
<view bindtap="example3"> detail example </view>
<view bindtap="example4"> touches example </view>
.js
example1:function(event){
console.log(event.type)
}
example2:function(event){
console.log(event.target)
}
example3:function(event){
console.log(event.detail)
}
example4:function(event){
console.log(event.touch
)
}
event.type: 返回通用事件类型
event.target: 触发事件的源组件。
event.detail : 带有的 x, y 代表距离文档左上角的距离
event.touch: