简体   繁体   中英

Is it possible to add event handlers to JavaScript functions/classes?

I am trying to register for events on a JavaScript function/class, and am trying to get it as close as possible to my C# class below. Is this possible in any way?

C#

public class MyClass
{
    public event EventHandler evtMyEvent;

    private void RaiseEvent()
    {
       if(evtMyEvent != null)
           evtMyEvent(this, new EventArgs());
    }
}

MyClass mc = new MyClass();
mc.evtMyEvent += (s,e) => { //Do Something };

JS

function MyClass()
{
    // Add an event handler...

    this.raiseEvent = function(){
        // raise the event
    }
}

var mc = new MyClass();
//register for the event

It's perfectly possible and you can study one of the many libraries that deal with events to check out their implementation.

Here is a very simplistic draft that doesn't handle unlistening, event types, arguments, scopes, bubbling etc:

function EventHandler(target) {  
  var listeners = [];

  this.add = function(handler) {
    listeners.push(handler);
  };

  this.fire = function() {
    for (var i=0; i<listeners.length; i++) {
      listeners[i].call(target);
    }
  };
}


function MyClass()
{
  this.name = 'myclass';

  // Add a private event handler...
  var eventHandler = new EventHandler(this);

  this.listen = function(f) {
    eventHandler.add(f);
  };
  this.raiseEvent = function(){
    eventHandler.fire();
  };
}

var mc = new MyClass();


mc.listen(function(){ console.log(this.name); });
mc.raiseEvent();

DEMO: http://jsbin.com/UCAseDi/1/edit

Obviously changes to this draft are easy to make. If you have trouble with either of them, let me know and i will try my best to help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM