This repository has been archived by the owner on Mar 31, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.co.js
96 lines (82 loc) · 2.58 KB
/
jquery.co.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* jQuery Condition Observer
* @copyright 2015, phoenixrvd
* @link https://github.com/phoenixrvd/co
* @license MIT
*/
;(function($){
var defConfig = {
// input-event for observing
event: 'change',
// event owns
controls: 'input:not([type=text]), select',
// elements for observing
elements: '[data-condition]',
// Defauls handler for visibility check
handler: function(){
var $this = $(this);
var defaultData = {
condition: false
};
var data = $.extend(defaultData, $this.data());
var condition = data.condition;
if(!condition){
return false;
}
var $matched = $(condition);
return ($matched.length != 0);
}
};
var self = function(config){
var conf = $.extend({}, defConfig, config);
var $area = (this.selector == '') ? $(document) : $(this.selector);
var observed = true;
var observer = {
start: function(){
observed = true;
},
stop: function(){
observed = false;
},
isRunned: function(){
return observed;
}
};
function handleCondition(){
var $this = $(this);
var elConf = $.extend({
customHandler: false
}, conf, $this.data());
var handler = elConf.handler;
var condition = elConf.condition;
var customHandler = elConf.customHandler;
if(customHandler){
handler = customHandler;
}else if(condition && condition.match("return") != null){
eval("handler = function(){" + condition + "}");
$this.data('customHandler', handler);
}
var visible = handler.call($this);
if(visible){
$this.show();
}else{
$this.hide();
}
}
function onObserveEvent(){
if(!observer.isRunned()){
return false;
}
observer.stop();
var $elements = $area.find(conf.elements);
$elements.each(handleCondition);
observer.start();
}
$area.bind("DOMSubtreeModified", onObserveEvent);
$area.on(conf.event, conf.controls, onObserveEvent);
$area.on('keyup', '[type=text], textarea', onObserveEvent);
onObserveEvent();
return self;
};
$.fn.co = self;
})(jQuery);