rivets-error-binder.js
3.25 KB
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
79
80
81
82
83
84
85
86
87
88
define(function(require) {
'use strict';
var module = require('module');
var rivets = require('rivets');
var $ = require('jquery');
var rivetsBinderCall = function(binding, binderName, methodName, args) {
var binder = rivets.binders[binderName];
binder[methodName].apply(binding, args);
};
var render = function(el, cmd, errorList) {
var viewClassPath = module.config().viewClassPath;
if (viewClassPath) {
var $el = $(el);
var view = $el.data('error-view');
if (view === undefined && cmd === 'bind') {
$el.data('error-view', null);
require([viewClassPath], function(ViewClass) {
$el.data('error-view', new ViewClass({el: el}));
});
return;
}
if (view) {
view.errorCallback(cmd, errorList);
}
return;
}
var renderImpl = module.config().render;
if (renderImpl) {
return renderImpl.apply(this, arguments);
}
};
rivets.binders['error-*'] = {
bind: function(el) {
var observer = this.observer;
var keyPath = observer.key.path;
var holder = this.validationHolder = {
//marker: el.parentNode.insertBefore(document.createComment(" rivets: " + this.type + " "), el),
observer: observer,
seen: {},
focus: function() {
render(el, 'focus', false);
},
blur: function() {
holder.seen[keyPath] = true;
render(el, 'blur', false);
if (observer.target) {
observer.target.validate();
}
},
validated: function(isValid, model, errors) {
var errorList = errors[keyPath];
if (errorList && holder.seen[keyPath]) {
render(el, 'validated', errorList);
} else {
render(el, 'validated', false);
}
}
};
$(el).on('focus', holder.focus).on('blur', holder.blur);
rivetsBinderCall(this, this.args[0], 'bind', arguments);
render(el, 'bind');
},
unbind: function(el) {
var holder = this.validationHolder;
render(el, 'unbind');
$(this.validationHolder.marker).after(el).remove();
$(el).off('focus', holder.focus).off('blur', holder.blur);
if (holder.observer.target) {
holder.observer.target.off('validated', holder.validated);
}
delete this.validationHolder;
rivetsBinderCall(this, this.args[0], 'unbind', arguments);
},
routine: function() {
var holder = this.validationHolder;
if (this.observer.target) {
this.observer.target.off('validated', holder.validated);
}
if (this.observer.target) {
this.observer.target.on('validated', holder.validated);
}
rivetsBinderCall(this, this.args[0], 'routine', arguments);
}
};
});