forked from kangax/protolicious
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathform_dispatcher.js
50 lines (48 loc) · 1.47 KB
/
form_dispatcher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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 element 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);
}
})