javascriptdom-eventsunobtrusive-javascript

How to add eventhandlers to prototype of an object in JavaScript


var MyObj = function(h,w){
   this.height = h;
   this.width  = w;
}

I would like to register some eventhandler for all instances of this object.

Say for example I would like to have a close button, when a user click on the button, it should close that specific Object.

So how to add eventhandlers to its prototype so that I can create these objects on the fly?


Solution

  • Event handlers are pretty much just functions that run when called at an appropriate time. It sounds like you want another object (ie: a button) to respond to an event, which then closes your object. In this case the button is the event listener, and not your object, so you would probably just set the onclick handler of the button to the appropriate close function on your object instance.

    If you really wanted to twist it the other way, you could do something really simple like so:

    var MyObj = function(h,w){
       this.height = h;
       this.width  = w;
    
       this.close = function(){ /** Do close */ }
       this.addCloser = function(closebutton){ closebutton.onclick = this.close(); }
    }
    

    which would be used like so:

    var myo = new MyObj();
    myo.addCloser(document.getElementById('mybutton'));
    

    However, if you want your object to generate events at which time registered handler functions are applied, you may want to do something more complex, like so:

    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]; 
           } 
       }
    
    
    
    }
    

    OR whatever, which could be use like so:

    var myo = new MyObj();
    myo.registerHandler('beforeclose', function(){alert("I'm closing!");});