Skip to content

Instantly share code, notes, and snippets.

@codethug
Created July 30, 2019 15:45
Show Gist options
  • Save codethug/47b646dafe7257979b6ab26a7801b0b6 to your computer and use it in GitHub Desktop.
Save codethug/47b646dafe7257979b6ab26a7801b0b6 to your computer and use it in GitHub Desktop.
A cookie extender for Knockout JS
// Uses the cookie library at https://github.com/js-cookie/js-cookie
// Usage: var firstName = ko.observable().extend({ cookie: "myFirstNameCookie" });
ko.extenders.cookie = function (target, option) {
var cookieName = option;
// Set the observable initially from the cookie value
target(Cookies.get(cookieName));
// Update the cookie when the observable updates
target.subscribe(function (newValue) {
Cookies.set(cookieName, newValue);
});
return target;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment