Skip to content

Instantly share code, notes, and snippets.

@svperfecta
Last active December 17, 2015 17:18
Show Gist options
  • Save svperfecta/5644646 to your computer and use it in GitHub Desktop.
Save svperfecta/5644646 to your computer and use it in GitHub Desktop.
Simple default values for KnockoutJS ViewModels
// Knockout, it's just javascript folks.
var Foo = function(data) {
var that = this;
/*
* ========
* Map Data
* ========
*/
// Default Data - If data doesn't exist, let's create an empty object
if (_.isUndefined(data)) data = {};
// Use Lodash (or Underscore) to provide a set of sane default values
data = _.defaults(data, {
bar: {},
baz: false,
qux: null
});
// Map Data using ko.mapping plugin
// Note: Optionally provide a mapping of course
ko.mapping.fromJS(data);
};
// Only provide certain values, and the rest are defaulted.
var viewModel = new Foo({
baz: true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment