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
|
var SerializableView = View.extend({
serialize: function(){
var fields = {}
this.$("input[name], select[name], textarea[name]").each( function(){
fields[this.name] = this.value
})
return fields
},
deserialize: function(data){
this.$("input[name], textarea[name]").val("")
Object.keys(data).forEach(function(k){
this.$("[" + k + "]").val(data[k])
})
},
validate: function(data){
var errors = []
var presence_msgs = this.validate_presence
Object.keys(presence_msgs).forEach(function(k){
if (! data[k]) errors.push( [ k, presence_msgs[k] ] )
})
return errors.length ? errors : null
},
show_errors: function(errors){
var msgs = []
errors.forEach(function(e){
this.$("[name=" + e[0] + "]").addClass('error_hilite')
msgs.push(e[1])
}.bind(this))
this.$msg.html(msgs.join("<br>"))
},
hide_errors: function(){
this.$msg.html("")
},
save: function(e){
e && e.preventDefault()
var data = this.serialize()
var errors = this.validate(data)
if (errors) {
this.show_errors(errors)
return
}
else {
this.hide_errors()
}
this.action({
data: data,
success: this.success.bind(this),
error: this.error.bind(this),
})
},
success: function(data){
console.log("SUCCESS", data)
},
error: function(data){
console.log("FAIL", data)
},
})
|