Created
January 4, 2016 18:42
-
-
Save jarroda/f0bd0507410a3cb8d21b to your computer and use it in GitHub Desktop.
Knockout + bootstrap-tagsinput
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ko.bindingHandlers.tagsinput = { | |
| init: function(element, valueAccessor, allBindings) { | |
| var options = allBindings().tagsinputOptions || {}; | |
| var value = valueAccessor(); | |
| var valueUnwrapped = ko.unwrap(value); | |
| var el = $(element); | |
| el.tagsinput(options); | |
| for(var i = 0; i < valueUnwrapped.length; i++) { | |
| el.tagsinput('add', valueUnwrapped[i]); | |
| } | |
| el.on('itemAdded', function(event) { | |
| if(valueUnwrapped.indexOf(event.item) === -1) { | |
| value.push(event.item); | |
| } | |
| }) | |
| el.on('itemRemoved', function(event) { | |
| value.remove(event.item); | |
| }); | |
| }, | |
| update: function(element, valueAccessor, allBindings, viewModel, bindingContext) { | |
| var value = valueAccessor(); | |
| var valueUnwrapped = ko.unwrap(value); | |
| var el = $(element); | |
| var prev = el.tagsinput('items'); | |
| var added = valueUnwrapped.filter(function(i) {return prev.indexOf(i) === -1;}); | |
| var removed = prev.filter(function(i) {return valueUnwrapped.indexOf(i) === -1;}); | |
| // Remove tags no longer in bound model | |
| for (var i = 0; i < removed.length; i++) { | |
| el.tagsinput('remove', removed[i]); | |
| } | |
| // Refresh remaining tags | |
| el.tagsinput('refresh'); | |
| // Add new items in model as tags | |
| for (i = 0; i < added.length; i++) { | |
| el.tagsinput('add', added[i]); | |
| } | |
| } | |
| }; |
Author
I've created a slightly improved version which also works, when you replace the bound array. You can find it in my fork.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://jsfiddle.net/kkspk0oq/3/