javascriptknockout.jsknockout-mapping-plugin

How to add an extender to each observable in knockout viewmodel?


i'm trying to add an extender to all my observables in my viewmodel. my data come from the server so i can't specify the properties one by one.

i tried this but it doens't work, i'm using the logChange extender from the knockout js webpage for this example.

var addingExtender = {
  key: function (data) {
        return data.id;
    },
  create: function(options) {
            return ko.observable(true).extend({ logChange: "Value Changed" });

    }
};
ko.mapping.fromJS(data, addingExtender, self);

Solution

  • I ended up doing a function to add the extender one by one.

    function addStorage(koViewModel,name) {
        for (var observableKey in koViewModel) {
            if (ko.isObservable(koViewModel[observableKey]) 
            && !isObservableArray(koViewModel[observableKey])) {
    
                koViewModel[observableKey].extend({ persist: name === undefined ?
                       url + observableKey : url + name +     "." + observableKey });
            }
    
            if (typeof koViewModel[observableKey] === "object") {
                for (var observables in koViewModel[observableKey]) {
                    if (ko.isObservable(koViewModel[observableKey][observables]) 
                    && !isObservableArray(koViewModel[observableKey][observables])) {
    
                        koViewModel[observableKey][observables].extend({ persist: url +
                               observableKey + "." + observables });
                    }
                }
            }
        }
    }