Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwritting observable/observableArray set method

Tags:

knockout.js

I am in the situation where I want to overwrite the set method that knockout has on observables; and to give you an example why I want that, take the following example code:

this.magic = ko.observableArray();

// ... inside an Ajax request
var formatted = reduceAndFormat(respone);
this.magic(formatted);

This is repeated a couple of times, so instead I would like to move the entire body of the reduceAndFormat function in the set method of a possibly customized observable.

Is there a way to do this? because outside of subscribing to observable updates didn't see much else in the documentation.

like image 754
mhitza Avatar asked Jan 16 '23 06:01

mhitza


1 Answers

You can create a writable computed observable

Something like this perhaps:

// private variable
this._magic = ko.observableArray();

// property with getter and setter
this.magic= ko.computed({
    read: function(){
        return _magic();
    },
    write: function(value) {
        var formatted = reduceAndFormat(value);
        this._magic(formatted);
    }
});    
like image 117
aaberg Avatar answered Jan 23 '23 16:01

aaberg