Simple Events in JavaScript

A couple of weeks ago I posted about C# like Properties in JavaScript. I wanted to explore how properties could possibly be added into JavaScript, and hopefully offer some insight into how some frameworks might work.

Another feature that JavaScript doesn’t explicitly support is events. Though using some of the same techniques I used for events also work very well for building events.

Most implementations of events in JavaScript use optional arguments in order to provide two overrides to an “event” function, one for adding a listener and the other for raising the event, like this:

// Add a handler
obj.click(objClicked);

function objClicked() {
}

// Raise the event
obj.click();

This provides a very straight forward to use interface (though doesn’t support unbinding.)

Below is a simple function for generating event functions that work in the way shown above.

In the returned “event” function I have no parameters, instead I check the inherent “arguments” object to see if there’s a single function parameter, and add it to “_handlers” if there is.

The for loop at the end raises the event by calling “apply” on the function and passing all the arguments from this method into it.

Use like such:

var MyClass = new function() {
  this.click = createEvent();
}

var obj = new MyClass();

obj.click(function (x, y) {
  alert('x: ' + x + ', y: ' + y);
});

obj.click(12, 24);

One Response to “ “Simple Events in JavaScript”

  1. vibox pc says:

    Hi, I do believe this is an excellent website.
    I stumbledupon it ;) I am going to revisit once again since
    I saved as a favorite it. Money and freedom is the best way to change, may you be rich and continue to guide other people.