MUI事件管理

模块事件管理

http://dev.dcloud.net.cn/mui/event/

事件绑定

除了可以使用addEventListener()方法监听某个特定元素上的事件外, 也可以使用.on()方法实现批量元素的事件绑定。

.on(event,select,handler);
//event: type:string,需要监听的事件名称,例如:"tap";
//select:type:string,选择器
//handler:type:function()事件触发时的回调函数,通过回调中的event参数可以获得事件详情

示例:

mui(".mui-table-view").on('tap','.mui-table-view-cell',function(){
  //获取id
  var id = this.getAttribute("id");
  //传值给详情页面,通知加载新数据
  mui.fire(detail,'getDetail',{id:id});
  //打开新闻详情
  mui.openWindow({
    id:'detail',
    url:'detail.html'
  });
}) 

事件取消

使用on()方法绑定事件后,若希望取消绑定,则可以使用off()方法。 off()方法根据传入参数的不同,有不同的实现逻辑。

.off(event,select,handler);
.off(event,select);
.off(event);
.off();//空参数,删除该元素上所有事件
//event: type:string,需取消绑定的事件名称,例如:'tap';
//select:type:string,选择器
//handler:type:function()之前绑定到该元素上的事件函数,不支持匿名函数

具体示例:

<script type="text/javascript">
mui("#list").on("tap","li",foo_1);//点击li时,执行foo_1函数
mui("#list").on("tap","li",foo_2);//点击li时,执行foo_2函数
function foo_1(){console.log("foo_1 execute");}
function foo_2(){console.log("foo_2 execute");}
// 第一种:off(event,selector,handle)适用于取消对应选择器上特定事件所执行的特定回调,例如:
mui("#list").off("tap","li",foo_1); //点击li时,不再执行foo_1函数,但会继续执行foo_2函数
// 第二种:off(event,selector)适用于取消对应选择器上特定事件的所有回调,例如:
mui("#list").off("tap","li");//点击li时,foo_2、foo_2两个函数均不再执行
// 第三种:off(event)适用于取消当前元素上绑定的特定事件的所有回调,例如:
mui("#list").off("tap");//点击li时,不再执行foo_1函数;点击p时,也不再执行foo_3函数
// 第四种:off()适用于取消当前元素上绑定的所有事件回调,例如:
mui("#list").off();//点击li时,不再执行foo_1函数;点击p时,也不再执行foo_3函数;双击li时,也不再执行foo_4函数;
</script>

事件触发

使用mui.trigger()方法可以动态触发特定DOM元素上的事件。

<script type="text/javascript">
.trigger(element,event,data);
//element:type: Element;触发事件的DOM元素
//event:type: String;事件名字,例如:'tap'、'swipeleft'
//data:type: Object; 需要传递给事件的业务参数
</script>

示例:自动触发按钮的点击事件

var btn = document.getElementById("submit");
//监听点击事件
btn.addEventListener("tap",function () {
  console.log("tap event trigger");
});
//触发submit按钮的点击事件
mui.trigger(btn,'tap');

手势事件

在开发移动端的应用时,会用到很多的手势操作,比如滑动、长按等,为了方便开放者快速集成这些手势,mui内置了常用的手势事件,目前支持的手势事件见如下列表:

分类参数描述
点击 tap 单击屏幕
doubletap 双击屏幕
长按 longtap 长按屏幕
hold 按住屏幕
release 离开屏幕
滑动 swipeleft 向左滑动
swiperight 向右滑动
swipeup 向上滑动
swipedown 向下滑动
拖动 dragstart 开始拖动
drag 拖动中
dragend 拖动结束

手势事件配置

根据使用频率,mui默认会监听部分手势事件,如点击、滑动事件;为了开发出更高性能的moble App,mui支持用户根据实际业务需求,通过mui.init方法中的gestureConfig参数,配置具体需要监听的手势事件。

mui.init({
  gestureConfig:{
   tap: true, //默认为true
   doubletap: true, //默认为false
   longtap: true, //默认为false
   swipe: true, //默认为true
   drag: true, //默认为true
   hold:false,//默认为false,不监听
   release:false//默认为false,不监听
  }
});

注意:dragstart、drag、dragend共用drag开关,swipeleft、swiperight、swipeup、swipedown共用swipe开关

事件监听

单个元素上的事件监听,直接使用addEventListener()即可,如下:

elem.addEventListener("swipeleft",function(){
     console.log("你正在向左滑动");
});

若多个元素执行相同逻辑,则建议使用事件绑定(on()) ;

自定义事件:仅能在5+ App及流应用中使用(因为是多webview之间传值,故无法在手机浏览器、微信中使用);

http://dev.dcloud.net.cn/mui/event/#customevent
原文地址:https://www.cnblogs.com/e0yu/p/7852501.html