8

I want to simulate C#'s events in JavaScript: what i want to do is something like this:

Let's say i have the following code:

function addToInvocationList(method, listener) {
      *Some code to add listener to the invocation list of method*
}

function MyClass() {
}

MyClass.prototype.Event = function() {}

var my_class_obj = new MyClass();

function subscriberFunction1() {}
function subscriberFunction2() {}
function subscriberFunction3() {}

addToInvocationList(my_class_obj.Event, subscriberFunction1);
addToInvocationList(my_class_obj.Event, subscriberFunction2);
addToInvocationList(my_class_obj.Event, subscriberFunction3);

my_class_obj.Event();

What i want to do is when i call my_class_obj.Event, all the subscribed functions get called.

Could this be achieved purely in JavaScript or i need to find my way around through DOM events?

2 Answers 2

9

How about writing a separate event class: Reference link: http://alexatnet.com/articles/model-view-controller-mvc-javascript

function Event(sender) {
    this._sender = sender;
    this._listeners = [];
}

Event.prototype = {
    attach: function (listener) {
        this._listeners.push(listener);
    },
    notify: function (args) {
        for (var i = 0; i < this._listeners.length; i++) {
            this._listeners[i](this._sender, args);
        }
    }
};

And your my class. For example:

function MyClass(name) {
     var self = this;
     self.Name = name;
     self.nameChanged = new Event(this);

     self.setName = function (newName){
         self.Name = newName;
         self.nameChanged.notify(newName);
     }
}

Subscribe to event example code:

var my_class_obj = new MyClass("Test");
my_class_obj.nameChanged.attach(function (sender,args){

});
my_class_obj.setName("newName");

You can attach more event handlers and all these event handlers will get called. And you can also add more events as you'd like: addressChanged event for example. This approach also simulate c# event (sender and args)

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

2 Comments

Exactly that's what i figured out, thanks man! This works great! However. i'm wondering about Garbage Collection, what if wanted to remove a handler, how can i make sure it's garbage collected, are anonymous methods garbage collected as soon are their reference is removed??
well, there should be no difference between anonymous methods and declared methods in this case. We also usually use anonymous methods in jQuery: $(document).ready(function(){});
0

You could write your own Observer (publisher-subscriber) read the GOF. Or, if using jQuery, custom events (http://api.jquery.com/trigger/) can help you out.

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.