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
1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.