Last active
February 14, 2018 17:44
-
-
Save 1tgr/c5ca67550b3ec1643a2d3d46e84a5eed to your computer and use it in GitHub Desktop.
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 = require('knockout'); | |
ko.observableDictionary = function(dict, valueFn) { | |
if (!valueFn) { | |
valueFn = function() { | |
return ko.observable(); | |
}; | |
} | |
var viewModels = {}; | |
var viewModelsObs = ko.observable(viewModels); | |
var items = ko.computed(function() { | |
viewModelsObs(); | |
return $.map(viewModels, function(value, key) { | |
return { key: key, value: value }; | |
}); | |
}); | |
var obs = ko.computed({ | |
read: function() { | |
var dict = {}; | |
var viewModels = viewModelsObs(); | |
$.each(viewModels, function(key, viewModel) { | |
dict[key] = viewModel(); | |
}); | |
return dict; | |
}, | |
write: function(newDict) { | |
var garbage = {}; | |
$.each(dict, function(key) { | |
garbage[key] = true; | |
}); | |
var mutated = false; | |
$.each(newDict, function(key, newValue) { | |
delete garbage[key]; | |
var viewModel = viewModels[key]; | |
if (viewModel === undefined) { | |
viewModels[key] = viewModel = valueFn(key); | |
mutated = true; | |
} | |
viewModel(newValue); | |
}); | |
$.each(garbage, function(key) { | |
delete viewModels[key]; | |
mutated = true; | |
}); | |
if (mutated) { | |
viewModelsObs.valueHasMutated(); | |
} | |
} | |
}); | |
obs.items = items; | |
obs(dict); | |
return obs; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment