forked from JamesKyburz/observable-form
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (42 loc) · 1.24 KB
/
index.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
51
52
var o = require('observable');
var em = require('events').EventEmitter;
module.exports = ObservableForm;
ObservableForm.prototype = Object.create(em.prototype);
function ObservableForm(form) {
if (!(this instanceof ObservableForm)) return new ObservableForm(form);
em.call(this);
this.form = form;
this.fields = {};
this.listeners = [];
this._observe();
}
ObservableForm.prototype._observe = function observe() {
this.cleanup();
var self = this;
[].forEach.call(this.form.querySelectorAll('input:not([type=radio]), select, textarea'), observeInput);
function observeInput(input) {
var name = input.getAttribute('name');
if (!name || input.disabled) return;
self.fields[name] = getObservable(input);
self.listeners.push(self.fields[name](change));
function change(value) {
self.emit('change', {name: name, value: value});
}
}
};
function getObservable(input) {
if (input.nodeName === 'SELECT') {
return o.select(input);
} else if (input.type === 'checkbox') {
return o.input(input, 'checked', 'change');
} else {
return o.input(input);
}
}
ObservableForm.prototype.cleanup = function cleanup() {
this.listeners.forEach(stop);
this.listeners = [];
function stop(f) {
f();
}
};