-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.dataform.js
78 lines (62 loc) · 1.76 KB
/
jquery.dataform.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
;(function($, window) {
function DataForm(attrs, onChange) {
this.attrs = attrs || [];
this.build();
this.onChange = onChange;
}
DataForm.registerElement = function(name, render, get, set) {
DataForm[name] = {
render: render,
get: get,
set: set
};
};
var proto = DataForm.prototype;
proto.build = function() {
var els = this.attrs.map(function(attr) {
return '<div class="j-dataform-el" data-type="'+attr.type+
'" data-name="'+attr.name+'">'+this.renderElement(attr)+'</div>';
}.bind(this)).join('');
this.html = '<form class="j-dataform">'+els+'</form>';
this.$el = $(this.html);
this.$el.data('dataform', this);
};
proto.renderElement = function(attr) {
if(!DataForm[attr.type]) throw attr.type + ' not registered';
return DataForm[attr.type].render.call(this, attr);
};
proto.getData = function() {
var obj = {};
this.$el.find('.j-dataform-el').each(function() {
var $this = $(this);
var val = getElementValue($this);
obj[$this.data('name')] = val;
});
return obj;
};
proto.setData = function(obj) {
obj = obj || {};
this.$el.find('.j-dataform-el').each(function() {
var $this = $(this);
var name = $this.data("name");
if(typeof obj[name] !== 'undefined')
setElementValue($this, obj[name]);
});
};
function getElementValue($el) {
var type = $el.data('type');
return DataForm[type].get($el);
}
function setElementValue($el, val) {
var type = $el.data('type');
return DataForm[type].set($el, val);
}
$('body').on('change', '.j-dataform-el', function(e) {
var $this = $(this);
var $f = $this.parents('.j-dataform');
var df = $f.data('dataform');
if(df.onChange)
df.onChange.bind(df)($this.data('name'), getElementValue($this));
});
window.DataForm = DataForm;
}) ($, window);