#150 enhancement
Morus Walter

Access to event in Form.Element.EventObserver

Reported by Morus Walter | June 6th, 2008 @ 12:27 PM | in 1.6.1

It would be great if the event that triggered the callback in an Form.EventObserver would be available in the callback.

While there are a lot of use cases where this is unnecessary, there are use cases where one needs to know which form element was acted on.

There used to be a ticket in the rails trac but that was closed without solution (http://dev.rubyonrails.org/ticke...).

After some hacking within prototype I managed to do a Form.EventObserver variant that does the job.

  Form.XEventObserver = Class.create();
  Form.XEventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
    getValue: function() {
      return Form.serialize(this.element);
    },
    onElementEvent: function( event ) {
      var value = this.getValue();
      if (this.lastValue != value) {
	this.callback(this.element, value, event);
        this.lastValue = value;
      }
    },
    registerCallback: function(element) {
      if (element.type) {
        switch (element.type.toLowerCase()) {
          case 'checkbox':
          case 'radio':
            Event.observe(element, 'click', this.onElementEvent.bindAsEventListener(this));
            break;
          default:
            Event.observe(element, 'change', this.onElementEvent.bindAsEventListener(this));
            break;
        }
      }
    }
    });

Changes basically are:

  • use bindAsEventListener instead of bind in registerCallback
  • provide the event as a third parameter of the callback

One issue I did not fix is, that the event object will be a "naked" event object as created by the browser without the extra methods provided by prototype. (I simply didn't care enough to figure out how to change that).

Comments and changes to this ticket

Please Login or create a free account to add a new comment.

You can update this ticket by sending an email to from your email client. (help)

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

The Prototype JavaScript library.

Shared Ticket Bins