如何在 JavaScript 中将事件处理程序添加到对象的原型中
How to add eventhandlers to prototype of an object in JavaScript
var MyObj = function(h,w){
this.height = h;
this.width = w;
}
我想为此对象的所有实例注册一些事件处理程序。
例如,假设我想要一个关闭按钮,当用户单击该按钮时,它应该关闭该特定对象。
那么如何将事件处理程序添加到其原型中,以便我可以动态创建这些对象呢?
事件处理程序几乎只是在适当时间调用时运行的函数。听起来您希望另一个对象(即:按钮(响应事件,然后关闭您的对象。在这种情况下,按钮是事件侦听器,而不是您的对象,因此您可能只是将按钮的 onclick 处理程序设置为对象实例上的相应关闭函数。
如果你真的想用另一种方式扭曲它,你可以做一些非常简单的事情,比如:
var MyObj = function(h,w){
this.height = h;
this.width = w;
this.close = function(){ /** Do close */ }
this.addCloser = function(closebutton){ closebutton.onclick = this.close(); }
}
将像这样使用:
var myo = new MyObj();
myo.addCloser(document.getElementById('mybutton'));
但是,如果您希望对象生成应用已注册处理程序函数的事件,则可能需要执行更复杂的操作,如下所示:
var MyObj = function(h,w){
this.height = h;
this.width = w;
this.handlers = {};
this.events = ['close', 'beforeclose'];
this.beforeClose = function(){
for(var i = 0, l = this.handlers.beforeclose.length; i < l; i++){
this.handlers.beforeclose[i].call(this);
}
}
this.afterClose = function(){
for(var i = 0, l = this.handlers.close.length; i < l; i++){
this.handlers.close[i].call(this);
}
}
this.close = function(){ this.beforeClose(); /**Do close */ this.afterClose(); }
this.registerHandler = function(type, func){
if(this.events.indexOf(type) == -1) throw "Invalid Event!";
if(this.handlers[type]){
this.handlers[type].push(func);
} else {
this.handlers[type] = [func];
}
}
}
或者其他什么,可以这样使用:
var myo = new MyObj();
myo.registerHandler('beforeclose', function(){alert("I'm closing!");});
相关文章:
- FabricJs-限制主对象内添加对象的移动区域
- 向Angular作用域对象添加对象数组——TypeError
- Javascript使用+添加对象
- 动态添加对象的jQuery事件处理程序
- 添加JQuery UI在Meteor中添加对象后可调整大小
- 在我的上下文中添加对象的动态方法
- 如何检测是否已使用 angular.forEach AngularJS 添加对象
- 在对象coffeescript中添加对象数组
- 使用Jquery在单击“”时显示表单;添加对象”;按钮
- 我可以向数组添加对象键吗
- 向扩展数组的JS集合添加对象(继承?)
- 尝试通过从自动完成推送添加对象时缺少 $$Hashkey
- 添加对象值 Javascript
- 在上传问题时添加对象
- 如何使用 javascript 的变量名称在数组中添加对象属性
- 在 JavaScript/TypeScript 中动态地“直接”添加对象属性到“this”
- 如何仅当对象不存在时才使用javascript添加对象
- 如何在数组末尾添加对象的副本
- rails在javascript url中添加对象
- ThreeJS-按不同顺序添加对象会影响alpha/显示