knockout.js - Knockout.Mapping - how to unmap when I've used a custom mapping? -
i use knockout.mapping
plugin not have moment object instead of crappy date:
var mappedpeople = ko.mapping.fromjs(people, { birthdate: { create: function(op) { return ko.observable( moment( new date(op.data) ) ); } } });
cool.
now, after making modifications want return entire array regular js. sounds job ko.mapping.tojs
!
but how go date? tojs
seems take options object can't seem find option helps this.
update: i'm aware in specific scenario of using moment.js there ways around issue coercing string , re-wrapping, underlying question how provide custom "unmapping" functions plugin.
update 2: here jsbin demonstrating issue: http://jsbin.com/uzesag/1/
i know not strictly speaking answering question of how customise unmapping itself, find useful way of handling type of situation wrap original data in observables, add computed observables (sub-observables) observables themselves. best illustrated example ...
jsbin showing moment added sub-observable on birthdate
the key snippet here ...
var mappedpeople = ko.mapping.fromjs(people, { birthdate: { create: function(op) { var observable = ko.observable(op.data); // attach computed 'birthdate' produces moment observable.moment = ko.computed({ read: function() { return moment( new date(observable()) ); }, write: function(val) { observable(val.todate().toisostring()); } }); return observable; } } });
this means when call ko.mapping.tojs or ko.mapping.tojson, original structure preserved. trick need store moment computed (to cause sync original data wrapped in observable) ...
function vm() { this.mapped = mappedpeople; // read moment computed var moment = this.mapped()[0].birthdate.moment(); // manipulate moment.add(5, 'y'); // set this.mapped()[0].birthdate.moment(moment); // unmapping this.unmapped = ko.mapping.tojson(this.mapped); } ko.applybindings(new vm());
Comments
Post a Comment