Last active
December 17, 2015 17:18
-
-
Save svperfecta/5644646 to your computer and use it in GitHub Desktop.
Simple default values for KnockoutJS ViewModels
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
// 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