Skip to content

Commit

Permalink
Add FormDispatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
kangax authored and kangax committed Apr 13, 2008
1 parent 4664767 commit 9b15618
Showing 1 changed file with 50 additions and 0 deletions.
50 changes: 50 additions & 0 deletions form_dispatcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
var Proto = Proto || { };

/**
* class Proto.FormDispatcher(element) -> Element
* - element(FormElement): element to observe
*
* Dispatches custom event when form's state changes.
* The event is dispatched by the form elements itself.
* Rules for determining state change can be customized via (static) Proto.FormDispatcher.rules
* Name of event can be changed via (static) Proto.FormDispatcher.eventName
*
* new Proto.FormDispatcher('myForm');
*
* document.observe('state:changed', function(e) {
* var element = e.memo.element;
* alert( element + ' was changed, and its value is now ' + $F(element) );
* })
*
**/
Proto.FormDispatcher = Class.create({
eventName: 'state:changed',
rules: {
'input[type=text]': 'keyup',
'textarea': 'keyup',
'input[type=checkbox]': 'click',
// TODO 'input[type=radio]': ''
'select': 'change'
},
initialize: function(element) {
if (!(this.element = $(element)))
throw new Error('Constructor requires DOMElement');

this.formElements = this.element.getElements();
this.initObservers();
},
initObservers: function() {
this.formElements.each(function(element) {
for (var rule in this.rules) {
if (element.match(rule)) {
element.observe(this.rules[rule], function() {
this.element.fire(Proto.FormDispatcher.eventName, {
element: element
});
}.bind(this));
return;
}
}
}, this);
}
})

0 comments on commit 9b15618

Please sign in to comment.