knockout.mapper.js
Knockout.mapper.js is a very simple plugin for knockout allowing you to:
- map object to a view model including validation, static fields, computed values, functions and custom bindings
- update a view model's values based on a model prototype
- can reset observables to the initial values they have been created by
- exports JSON by a model prototype
License: MIT
Usage
// Let's have a model prototype. (could have been received from server-side or define any way you want to...)var obj = {};// Knockout static propertiesobjstatics = "prop": "val";// Knockout data model itself - including custom bindingsobjdataModel = firstName: "Planet" lastName: "Earth" { return this + " " + this; } name: { return this + " " + this; } { var lastSpacePos = value ? value : 0; if lastSpacePos > 0 // Ignore values with no space character this; // Update "firstName" this; // Update "lastName" } owner: this ;// Knockout methods to be added to the modelobjmethods = { var currentVal = this; this; } { console; };// validation rules definedobjvalidation = firstName: required: true type: "alphanum" lastName: notblank: true type: "alphanum" ; var viewModel = {}; // map your JS object to have a knockout viewmodelko; // apply bindings as usualko; objdataModelfirstName = "Universe";// updating the viewmodel based on some changes might received from server-sideko; // resets the firstName and lastName to the initial values "Planet" and "Earth"ko; // print out the JSON containing only the fields possessed by the prototype passed by. Much faster, than the toJSON of knockout and can be targeted only content you are really interested inconsole;