var MyObj = function(h,w){
this.height = h;
this.width = w;
}
我想爲此對象的所有實例註冊一些事件處理程序。如何將事件處理程序添加到JavaScript中的對象的原型中
說例如我想要一個關閉按鈕,當用戶點擊按鈕,它應該關閉該特定的對象。
那麼如何添加eventhandlers到它的原型,以便我可以即時創建這些對象。
var MyObj = function(h,w){
this.height = h;
this.width = w;
}
我想爲此對象的所有實例註冊一些事件處理程序。如何將事件處理程序添加到JavaScript中的對象的原型中
說例如我想要一個關閉按鈕,當用戶點擊按鈕,它應該關閉該特定的對象。
那麼如何添加eventhandlers到它的原型,以便我可以即時創建這些對象。
事件處理程序幾乎只是在適當的時候調用時才運行的函數。這聽起來像你想要另一個對象(即:一個按鈕)來響應一個事件,然後關閉你的對象。在這種情況下,按鈕是事件監聽器,而不是您的對象,因此您可能只需將按鈕的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!");});
+1優雅的解決方案:) – nepsdotin 2012-01-06 10:41:31
是什麼*接近特定對象*是什麼意思?這樣的對象是做什麼的?你必須提供更多信息。事件處理程序只是功能。 – 2012-01-06 09:09:01
可以有多個對象的實例,當我關閉一個對象時,應該關閉對象而不是其他對象。 – nepsdotin 2012-01-06 11:02:54