イベントハンドラは、適切なタイミングで呼び出されたときに実行される関数です。別のオブジェクト(つまり、ボタン)がイベントに応答してオブジェクトを閉じるようにしたいと思うようです。この場合、ボタンはオブジェクトではなくイベントリスナーです。そのため、ボタンのonclickハンドラをオブジェクトインスタンスの適切なclose関数に設定するだけです。あなたが本当にそれを他の方法をねじるしたい場合
は、あなたがそうのように本当に簡単な何かができる:そうのように使用されるだろう
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!");});
*特定のオブジェクト*の意味は何ですか?そのようなオブジェクトは何をしていますか?より多くの情報を提供する必要があります。イベントハンドラは単なる関数です。 –
オブジェクトを閉じるときにオブジェクトを複数インスタンス化することができます。そのオブジェクトは他のものではなく閉じなければなりません。エレガントなソリューションのために – nepsdotin