Search code examples
javascriptprototypejsdom-eventsjavascript-framework

Event Binding/ Unbinding with Prototype


I want to observe for two custom events via the prototype framework and unbind one of them.

Meaning, when the browser loads the DOM elements, I want to register the following events: "customEvent:Task1" and "customEvent:Task2". These two events are observed on the whole page.

When "customEvent:Task1" is called/executed, I want to unbind/ unregister the "customEvent:Task2" event on the page. When "customEvent:Task2" is called, it just executes a function.

So how can I register (bind) and unregister (unbind) events using the prototype framework.

Edit: The registered customEvents are not bound to an element but are available through out the page. I hope this makes sense.


Solution

  • You would use Event.on for something global like the document itself:
    (Event.on is new to Prototype 1.7)

    document.on('customEvent:Task1', function(event, element) {
        if (customEventTask2) customEventTask2.stop();
    });
    var customEventTask2 = document.on('customEvent:Task1', function(event, element) {
        // This is your second event type
    });
    

    Then of course all that remains is to fire some events.

    document.fire('customEvent:Task1');
    document.fire('customEvent:Task2'); // Should not fire