Modifying the behaviour of a class using Ojay.Observable’s class-level listeners

When setting up event listeners in the DOM, you often specify a type of object to listen to, rather than a specific instance. For example, you call Ojay('p').on(...), or Ojay('.gallery-item').on(...). Ojay.Observable provides a similar mechanism for JavaScript classes, in that it allows you to register event listeners on a class, and have those listeners fire whenever an instance of said class fires the relevant event.

In this example, we set up event listeners on the Ojay.Accordion.Section class in order to modify the behaviour of all accordion menus. Our event listeners cause the accordion sections to change opacity as they change height. The listeners are passed a reference to the section firing each event so they can perform their action.

Note that accordion sections are actaully instances of either Accordion.VerticalSection or Accordion.HorizontalSection; since events ‘bubble’ up the inheritance tree from the objects that fire them, the parent class Accordion.Section can be used to catch events from all types of accordion section.

JavaScript source code

Stylesheet