Classic Javascript/Actionscript event handlers in MVC

Event handlers are the “Controller” part of MVC in a page.

In most situations, the controller needs to be instantiated when data are ready (for example, when an xml stream is parsed). When triggered, controller often leads to events that display data. It is often convenient to directly attach data to the visual objects that the event handlers are attached to, so that when triggered, the event handler function can grab the data by simply referring to “this.data” since the “this” is scoped to the visual object at the moment the event handler is attached to it. Handy data are good, but this confuses model with presentation and also results in redundant data. One trick I played recently was to build an index attribute in the visual object that serves as sort of a lookup table for relevant data. The data are stored in a seperate object (centralized as model) and can be accessed by different controllers.

The followings are the snippets of code in action:

//When data are available, loop through the data and do all the mover’s job while we initialize/define the event handler

The above snippet of code is the more “conventional” way of assigning an event handler. In a more OO way, it can be something like this (due to different implementations of event handling in javascript, there is now no consistent way across browsers):

The event handler is wrapped up in a function call that passes on all the data chunks as parameters to the former. This somehow serves as a machanism to (misteriously) keep track of which controller is associated with which piece of data (like the gmarker<->infoTabs pair) without assigning the data as dynamic attributes to the controller objects.

So to sum it up, the steps are:

1. Query and parse data;

2. Define and attach the event handlers when parsing the data.

3. Build lookup attribute as attribute of the visual object that the event handler is attached to; or simply attach relevant snippet data directly to the visual objects when data don’t need to be shared across multiple controllers; or in a more OO way, pass the data as parameters directly when defining/assigning the event handlers.