#150 enhancement
Morus Walter

Access to event in Form.Element.EventObserver

Reported by Morus Walter | June 10th, 2008 @ 05:09 PM | in 1.7

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 Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

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

Pages