javascript - JS面向对象时,组件的click事件怎么调用自身的方法?
本文介绍了javascript - JS面向对象时,组件的click事件怎么调用自身的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
在《你不知道的JS》中,有一个委托控件对象的例子,使用了jquery,我想用原生js改写
其中遇到这句this.$el.click(this.onClick.bind(this));
改写一直失败。麻烦各位可以给我解惑。
我的方案
结果点击按钮控制台无反应
Button.build=function($where){
this.insert($where);
this.$el.onclick=function(){
Button.onClick.bind(this);
}
};
点击控制台显示
Button "undefined" clicked!
Button.build=function($where){
this.insert($where);
this.$el.onclick=function(){
Button.onClick.call(this);
}
};
点击后显示
Uncaught TypeError: Cannot read property 'call' of undefined
Button.build=function($where){
this.insert($where);
this.$el.onclick=function(){
this.onClick.call(this);
}
};
分析
this.$el.onclick之后,console.log(this),显示的是一个dom元素<button>xxx</button>
疑问
组件绑定click事件如何调用自身的方法?jquery是如何实现这个绑定的?
谢谢大家!
源代码:
var Widget = {
init: function(width, height) {
this.width = width || 50;
this.height = height || 50;
this.$el = null;
},
insert: function($where) {
if (this.$el) {
this.$el.css({
width: this.width + 'px',
height: this.height + 'px'
}).appendTo($where);
}
}
};
var Button = Object.create(Widget);
Button.setup = function(width, height, label) {
this.init(width, height);
this.label = label || 'default';
this.$el = $('<button>').text(this.label);
};
Button.build = function($where) {
this.insert($where);
this.$el.click(this.onClick.bind(this));
};
Button.onClick = function(e) {
console.log('Button "' + this.label + '" clicked!');
};
$(document).ready(function() {
var $body = $(document.body);
var btn1 = Object.create(Button);
btn1.setup(125, 30, 'Hello');
var btn2 = Object.create(Button);
btn2.setup(150, 40, 'World');
btn1.build($body);
btn2.build($body);
});
解决方案
btn.onclick = Button.onClick.bind(this)
这篇关于javascript - JS面向对象时,组件的click事件怎么调用自身的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文