-
Notifications
You must be signed in to change notification settings - Fork 2
/
ko-multi-wrapper.js
61 lines (49 loc) · 3 KB
/
ko-multi-wrapper.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
// ko-multi-wrapper.js
// Copyright (c) 2012, Eric Panorel
// License: MIT (http://www.opensource.org/licenses/mit-license.php)
//
// Knockout binding for Eric Hynd's jQuery UI MultiSelect Widget
//
// http://www.erichynds.com/jquery/jquery-ui-multiselect-widget/
//
// This binding wraps the standard 'options' binding for SELECT
// html element, with mutiple attribute (multi-select).
// Examples:
// <select data-bind="multiSelectCheck: listOfObjects, optionsCaption: 'Check one or more', selectedOptions: selectedRec, optionsText: 'Key'" multiple="multiple"></select>
// <select data-bind="multiSelectCheck: listOfString, optionsCaption: 'Check one or more', selectedOptions: selectedRec" multiple="multiple"></select>
(function (ko, $) {
if (typeof (ko) === undefined) { throw 'Knockout is required, please ensure it is loaded before loading this plug-in'; }
if (typeof (jQuery) === undefined) { throw 'jQuery is required, please ensure it is loaded before loading this plug-in'; }
if (typeof (jQuery.ui) === undefined) { throw 'jQuery UI is required, please ensure it is loaded before loading this plug-in'; }
// private functions here
// the binding
ko.bindingHandlers.multiSelectCheck = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
var multiselectOptions = ko.utils.unwrapObservable(allBindingsAccessor().multiselectOptions) || {};
// pass the original optionsCaption to the similar widget option
if (ko.utils.unwrapObservable(allBindingsAccessor().optionsCaption)) {
multiselectOptions.noneSelectedText = ko.utils.unwrapObservable(allBindingsAccessor().optionsCaption);
}
// remove this and use the widget's
allBindingsAccessor().optionsCaption = '';
$(element).multiselect(multiselectOptions);
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).multiselect("destroy");
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
var selectOptions = ko.utils.unwrapObservable(allBindingsAccessor().multiSelectCheck);
// remove this and use the widget's
allBindingsAccessor().optionsCaption = '';
ko.bindingHandlers.options.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
setTimeout(function () {
$(element).multiselect("refresh");
}, 0);
}
};
})(ko, jQuery);