john
john

Reputation: 857

Prototype Event.observe alternative?

I am used Event.observe method to bind an event; this method is defined in the Prototype library.

Event.observe(clickElem, "click", function(event) {
    //operations
});

I am going to remove Prototype from my code.

Is there any alternative for Event.observe in plain JavaScript?

Upvotes: 1

Views: 1438

Answers (1)

Jeremy
Jeremy

Reputation: 792

Yes, standard and legacy IE event handlers:

// standard
clickElem.addEventListener("click", function(evt) {

}, false);

// legacy IE
clickElem.attachEvent("onclick", function(evt) {

});

It's typical to see some helper functions to facilitate cross-browser event handlers.

function addEvent(elem, eventName, fn) {
    if (typeof addEventListener !== "undefined") {
        elem.addEventListener(eventName, fn, false);
    } else {
        elem.attachEvent("on" + eventName, fn);
    }
}

// calling
addEvent(clickElem, "click", function(evt) {
    alert("You clicked me.");
});

If you're not going to use Prototype, then you'll have to handle the discrepancies between the two event models on your own. If you plan on using another library/framework, then you'll want to use that library's/framework's API.

Upvotes: 5

Related Questions