UNPKG

2.12 kBJavaScriptView Raw
1
2var Tag = require('./tag'),
3 wrappers = require('./wrappers');
4
5var Form = module.exports = function Form (options, elements) {
6
7 // default the options object
8 this.options = options || {};
9
10 // default the attributes object
11 this.attributes = this.options.attributes || {};
12
13 // default the elements object
14 this.elements = elements || [];
15
16 // default the render value
17 this.renderTag = (this.options.renderTag === undefined) ? true : this.options.renderTag;
18
19 // default the theme object
20 this.options.theme = this.options.theme || {};
21
22 // default the form wrapper to no-op
23 this.options.theme.form = this.options.theme.form || wrappers.noop;
24
25 // default the fieldset wrapper to no-op
26 this.options.theme.fieldset = this.options.theme.fieldset || wrappers.noop;
27
28 // default the fieldgroup wrapper to div
29 this.options.theme.fieldgroup = this.options.theme.fieldgroup || {};
30
31 this.options.theme.fieldgroup.group = this.options.theme.fieldgroup.group || wrappers.fieldgroup.group;
32
33 this.options.theme.fieldgroup.fields = this.options.theme.fieldgroup.fields || wrappers.fieldgroup.fields;
34
35 this.options.theme.fieldgroup.field = this.options.theme.fieldgroup.field || wrappers.fieldgroup.field;
36
37 // default the field wrapper to div
38 this.options.theme.field = this.options.theme.field || wrappers.field;
39
40 // default the input wrapper to no-op
41 this.options.theme.control = this.options.theme.control || wrappers.noop;
42
43};
44
45Form.prototype.render = function (callback) {
46
47 var content = '',
48 tag,
49 html;
50
51 for (var i = 0; i < this.elements.length; i++) {
52 content += this.elements[i].render(this.options.theme);
53 }
54
55 tag = new Tag('form', this.attributes, content);
56
57 html = this.options.theme.form((this.renderTag === true ? tag.render() : content), this);
58
59 if (callback) {
60 return callback(html);
61 }
62
63 return html;
64
65};
66
67Form.prototype.add = function (elObject) {
68
69 this.elements.push(elObject);
70
71 return elObject;
72
73};
74
75Form.prototype.attribute = function (key, value) {
76
77 if (value === undefined) {
78 return this.attributes[key];
79 }
80
81 this.attributes[key] = value;
82
83 // for chaining
84 return this;
85
86};
\No newline at end of file