阅读了官方文档,你会发现。微信的事件绑定输入的是字符串。字符串绑定带来的问题包括,把方法堆积在一个js文件里,这是项目开发致命的问题!
事件绑定
原方法
文件树
–pages
----test.js
----test.wxml
test.wxml
<view bindtap="clickView" bindlongpress="catchView"></view>
test.js
Page({
clickView(e){
console.log(e);
},
catchView(e){
console.log(e);
}
})
基于普通方案实现的事件绑定将所有方法,如示例中的clickView堆积在Page中,这相当不方便维护。
修正方案
文件树
–pages
----test.js
----test.wxml
–Ext
----Ext.js
test.wxml
<view bindtap="ext" bindlongpress="ext" data-func="oneView"></view>
test.js
import {Ext} from '../Ext/Ext.js';
Page({
onLoad:function(e){
this.ext=new Ext();
},
ext(e) {
let {type}=e;
let {func}=e.currentTarget.dataset;
this.ext[func][type].bind(this)(e);
}
})
Ext.js
class Ext{
constructor(e){
console.log(e);//构造函数
}
oneView={
tap(e){console.log(e)},
longpress(e){console.log(e)}
}
}
export {Ext}
通过type属性以及data-func,我们可以成功使得将事件绑定到了另一个对象中,将代码块转移到另一个文件。
意义
- 变相支持对象内事件绑定
- 支持模块化开发
- bug:catchtap和bindtap的区别在事件中无法体现,怎么办呢?有区别的意义么
版权规定
- 署名(Attribution,简写为BY):必须提到原作者。
- 非商业用途(Noncommercial,简写为NC):不得用于盈利性目的。在CSDN上转载,将被认为赚取流量,为盈利目的
- 禁止演绎(No Derivative Works,简写为ND):不得修改原作品, 不得再创作。
- 相同方式共享(Share Alike,简写为SA):允许修改原作品,但必须使用相同的许可证发布。