ko.mapping.fromJS and dependantObservables

58 views
Skip to first unread message

jeffrey...@googlemail.com

unread,
Mar 11, 2015, 8:01:43 AM3/11/15
to knock...@googlegroups.com
I need to perform Crud operations in the UI, and am using knockoutjs and the mapping plugin to do it.

However when I call toJS followed by fromJS my dependant observable function gets overwritten.

Please, how do I maintain the dependant observable as a computed function through serialisation and deserialisation with the mapping plugin?

function clientViewModel() {
    var self = this;

  self.addresses = ko.observableArray();
  self.selectedAddress = ko.observable();
  self.addressForEditing = ko.observable();

  self.addAddress = function (data, e) {
    self.addressForEditing(new address());
   };

    self.addAddressSave = function (data, e) {
        var newAddress = ko.observable(new address());
        ko.mapping.fromJS(ko.mapping.toJS(self.addressForEditing), {}, newAddress)
        self.addresses.push(newAddress);
    };

    self.editAddress = function (data, e) {
        self.selectedAddress(data);
        ko.mapping.fromJS(ko.mapping.toJS(self.selectedAddress), {}, self.addressForEditing);
    };

    self.editAddressSave = function (data, e) {
        ko.mapping.fromJS(ko.mapping.toJS(self.addressForEditing), {}, self.selectedAddress);
    };
};

function address() {
  var self = this;

    self.Property = ko.observable("");
   self.Street = ko.observable("");
    self.Town = ko.observable("");
   self.Postcode = ko.observable("");
  self.Country = ko.observable("");
  
  self.FullAddress = ko.computed(function () {
        var arr = [" ", self.Property(), self.Street(), self.Town(), self.Postcode()];

        return arr.join(", ").split(" ,").join("").trim();    
    }, this);
};


When adding a new address the FullAddress is a computed function.  
However when editing an existing address the ko.mapping call transposes FullAddress to a string on addressforediting.

Any clues?

thanks

Noirabys

unread,
Mar 16, 2015, 12:53:56 PM3/16/15
to knock...@googlegroups.com, jeffrey...@googlemail.com
hi,
....the join() method joins the elements of an array into a string, and returns the string.
thus self.FullAddress is a string ... 

you can use a viewmodelmapping , thats the second paramter of the mapping tool

if you need transactional support i would recommend an extender for example have a look at:

for simple structures its easier to initialize by construcor

function Address(data){
   var self = this;
    self.name = ko.observable(data.name);
}

you can initialize arrays:

self.addresses = ko.observableArray(ko.utils.ArrayMap(data,function(adress){ return new Address(adress); });
Reply all
Reply to author
Forward
0 new messages