Skip to content

Instantly share code, notes, and snippets.

@losnir
Created February 22, 2015 11:14
Show Gist options
  • Save losnir/4ef2dfc818fe8a824994 to your computer and use it in GitHub Desktop.
Save losnir/4ef2dfc818fe8a824994 to your computer and use it in GitHub Desktop.
Knockout Utilities
/**
* A recursive deep-cloning utility, specifically for KO ViewModels.
* @author Nir Azuelos
* @param {object} input
* @returns {object} output
*/
ko.utils.clone = function(input) {
var mapped = ko.mapping.fromJS(input, {
create: function (options) {
return ko.mapping.visitModel(options.data, function (value, parent) {
var mapped = value;
if(parent && value && typeof value === "object")
mapped = ko.utils.clone(value);
if (ko.isObservable(mapped)) return ko.observable(mapped.peek());
return mapped;
});
}
});
delete mapped["__ko_mapping__"];
return mapped;
}
/**
* A small handy observable / computed function to toggle it's boolean value.
* @author Nir Azuelos
* @returns {Function}
*/
ko.observable.fn.toggle = ko.computed.fn.toggle = function(state) {
this(typeof state === "boolean" ? state : !this());
};
/**
* A small handy observable / computed function that wraps around the inverse of it's boolean value.
* @author Nir Azuelos
* @returns {Function}
*/
ko.observable.fn.inverse = ko.computed.fn.inverse = function() {
return ko.pureComputed(function() { return !this(); }, this);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment