0

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
GJHix
  • 522
  • 10
  • 18
  • You could look at using server push for something like this, see http://stackoverflow.com/questions/5378383/looking-for-comet-style-server-or-client – andy mccullough Nov 07 '13 at 11:46

1 Answers1

1

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.

Tibos
  • 27,507
  • 4
  • 50
  • 64