forked from snap-cloud/snapcon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathosem-switch.js
More file actions
92 lines (74 loc) · 2.68 KB
/
osem-switch.js
File metadata and controls
92 lines (74 loc) · 2.68 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
89
90
91
92
function checkboxSwitch(selector){
$(selector).bootstrapSwitch();
// Prevent duplicated event handlers when the page is re-rendered.
$(selector).off('switchChange.bootstrapSwitch');
$(selector).off('.osemSwitchGuard');
// Mark as user-initiated before bootstrapSwitch triggers switchChange.
// Important: bootstrapSwitch often binds clicks on its generated wrapper/label,
// so we must listen on those too (not only on the hidden checkbox input).
$(selector).each(function() {
var $input = $(this);
$input.data('osem-user-toggle', false);
var $wrapper = $input.closest('.bootstrap-switch');
if ($wrapper.length === 0) {
$wrapper = $input.parent();
}
$wrapper.off('click.osemSwitchGuard mouseup.osemSwitchGuard touchend.osemSwitchGuard pointerup.osemSwitchGuard');
$wrapper.on(
'click.osemSwitchGuard mouseup.osemSwitchGuard touchend.osemSwitchGuard pointerup.osemSwitchGuard',
function() {
$input.data('osem-user-toggle', true);
}
);
});
$(selector).on('switchChange.bootstrapSwitch', function(_event, state) {
var $el = $(this);
if (!$el.data('osem-user-toggle')) {
return;
}
// bootstrapSwitch can emit multiple switchChange events per user click.
// Delay the request slightly, then read the final checkbox state to send once.
var existingTimer = $el.data('osem-user-toggle-timer');
if (existingTimer) {
clearTimeout(existingTimer);
}
var method = $el.attr('method') || 'patch';
var urlBase = $el.attr('url');
var timer = setTimeout(function() {
$el.data('osem-user-toggle', false);
var checked = $el.is(':checked');
var url = urlBase + (checked ? 'true' : 'false');
$.ajax({
url: url,
type: method,
dataType: 'script'
});
}, 180);
$el.data('osem-user-toggle-timer', timer);
});
}
$(function () {
$.fn.bootstrapSwitch.defaults.onColor = 'success';
$.fn.bootstrapSwitch.defaults.offColor = 'warning';
$.fn.bootstrapSwitch.defaults.onText = 'Yes';
$.fn.bootstrapSwitch.defaults.offText = 'No';
$.fn.bootstrapSwitch.defaults.size = 'small';
checkboxSwitch("[class='switch-checkbox']");
$("[class='switch-checkbox-schedule']").bootstrapSwitch();
$('input[class="switch-checkbox-schedule"]').on('switchChange.bootstrapSwitch', function(event, state) {
var url = $(this).attr('url');
var method = $(this).attr('method') || 'patch';
if(state){
url += $(this).attr('value');
}
var callback = function(data) {
showError($.parseJSON(data.responseText).errors);
}
$.ajax({
url: url,
type: method,
error: callback,
dataType: 'json'
});
});
});