jQuery $.on()方法和addEventListener改变this指向

标签(空格分隔): jQuery JavaScript


jQuery $.on()

jq的绑定事件使用$([selector]).on([types], [selector], [data], [fn], [one])方法;解绑事件使用off,但是解绑具体事件时候handler只能是具名函数。

在一个对象中,当我们想要在具名函数中用this访问当前对象的属性,可以从[data]参数传入,然后在具名函数中通过e.data来访问:

var obj = {
options: { a: 1 },
init: function() {
$(window).off('click', this._event);
$(window).on('click', { self: this }, this._event);
},
_event: function(e) {
var self = e.data.self;
console.log(self.options);
}
};

addEventListener

详细内容参见MDN

addEventListener兼容性

1. 通过bind(this)方法

var Foo = function (ele) {
this.name = 'This is foo';
this.onclickA = function (e) {
console.log(this.name); // undefined
};
this.onclickB = function (e) {
console.log(this.name); // This is foo
}; ele.addEventListener('click', this.onclickA, false);
ele.addEventListener('click', this.onclickB.bind(this), false);
}; new Foo(document.body);

2. 通过定制的函数handleEvent去捕获任意类型

var Bar = function (ele) {
this.ele = ele;
this.name = 'This is bar';
this.handleEvent = function (e) {
console.log(this.name);
switch (e.type) {
case 'click':
console.log('Trigger click...');
break;
case 'dblclick':
console.log('Trigger dblclick...');
break;
}
}; ele.addEventListener('click', this, false);
ele.addEventListener('dblclick', this, false);
};
Bar.prototype.remove = function () {
// 你也可以移除这些监听事件
this.ele.removeEventListener('click', this, false);
this.ele.removeEventListener('dblclick', this, false);
}; var bar = new Bar(document.body);
bar.remove();

3. 给EventListener传递一个函数,调用想要访问对应作用域对象的方法

但是这样做绑定的事件成为了匿名函数,是不能取消绑定的。

class SomeClass {
constructor() {
this.name = 'This is a class';
} register() {
const that = this;
window.addEventListener('keydown', function (ev) { return that.foo(ev); });
} foo(e) {
console.log(this.name);
switch (e.keyCode) {
case 65:
console.log('a');
break;
case 13:
console.log('enter');
break;
}
}
} const obj = new SomeClass();
obj.register();

随机推荐

  1. input输入框中只能输入数字,非数字字符自动清除

    前言:项目中有个缴纳保证金的功能,要是输入框只能输入数字,不能输入其他字符. ①HTML代码:<input class="input-box" type="text ...

  2. Stirng,Stringbuffer,Stringbuild的区别浅淡

    String 1,Stirng是对象不是基本数据类型 2,String是final类,不能被继承.是不可变对象,一旦创建,就不能修改它的值. 3,对于已经存在的Stirng对象,修改它的值,就是重新创 ...

  3. IE浏览器报Promise未定义

    用vue-cli做的项目,用了promise,结果IE下报promise未定义,甚至在比较老的andriod手机浏览器上会显示空白页面,解决方案如下: 首先安装:babel-polyfill npm ...

  4. ddddddeeeessssssttttrrrrrrooooooyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

    我遥远的 POI 计划啊 https://loj.ac/problems/search?keyword=POI2011 atcoder 一套 动态 DP SAM 随便看 XSY 的题 UOJ Roun ...

  5. easyui导出当前datagrid数据(Word)

    JS代码可参考http://www.cnblogs.com/mu1516633121/p/7753423.html 同样是winform架构下应用到Aspose.Words来读写Word文档 其中Se ...

  6. 智能提示含查询多列(html+JS+handler+ HttpRemoting)二、Remoting代码

    /// <summary> /// 智能查询类型 /// </summary> public enum QueryType : byte { /// <summary&g ...

  7. Javascript与jQuery方法的隐藏与显示

    如题,代码奉上. <html> <head> <title>denotoggle</title> <style> #box { width: ...

  8. 九、cent OS下tomcat改变日志目录

    修改catalina.out的目录bin目录下修改catalina.sh:CATALINA_OUT="$CATALINA_BASE"/logs/catalina.out  此行内的 ...

  9. Spring_Spring与IoC_基于注解的DI

    一.基本注解的使用 (1)导入AOP的Jar包 (2) 与set()无关 二.组件扫描器的base-package 三.@Component相关注解 四.@Scope 五.域属性的注入 (1)byTy ...

  10. dokcer安装并开机自启动服务

    linux内核最好是3.10以上.不过本次使用的是centos6.5 内核2.6 1.yum -y install docker-io 如果出现: 需要安装yum源: 3.service docker ...