-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (71 loc) · 2.19 KB
/
index.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
var Select = require('select');
/**
* Expose `plugin`
*/
module.exports = reactiveSelect;
/**
* Reactive Select
*/
function reactiveSelect(reactive) {
reactive.bind('select', function(el, name, model) {
var label = el.getAttribute('select-label') || '';
var multiple = el.hasAttribute('select-multiple');
var options = this.value(el.getAttribute('select-options'));
var select = Select().label(label);
var view = this.view;
// If no options, no select
if (!options || !Array.isArray(options)) return;
// Allow multiple selection
if (multiple) select.multiple();
// Add all options
options.forEach(function(item) {
if (typeof item === 'string') select.add(item, item);
else select.add(item.name, item.value, item.el);
});
// On selection change
this.change(function() { selectItems(select, this.value(name)); });
// Update model on selection changes
select.on('change', function() {
var values = select.values();
if (multiple) model[name](values);
else model[name](values[0]);
});
// Append the select to this div
el.appendChild(select.el);
// Add to `_selects` object
view._selects = view._selects || {};
view._selects[name] = select;
// Create `select` function if it does not exist
if (!view.select) {
view.select = function(name) {
return this._selects[name];
};
}
});
}
/**
* Select items, deselect items no longer existing in the array
*/
function selectItems(select, items) {
if (items) {
if (!Array.isArray(items)) items = [ items ];
select.selected().forEach(function(selected) {
var contains = false;
items.forEach(function(item) {
var name = item;
if (typeof item !== 'string') name = item.name;
if (selected.value === name) contains = true;
});
if (!contains) select.deselect(selected.name);
});
items.forEach(function(item) {
var name = item;
if (typeof name !== 'string') name = item.name;
if (!select.get(name).selected) select.select(name);
});
} else {
select.selected().forEach(function(selected) {
select.deselect(selected.name);
});
}
}