Pregunta

A lot of times I use the following code in my knockout applications:

function VM_someModel(){
    var self = this;

    this.type1 = {
        a1       : ko.observable(false),
        a2       : ko.observable(false),
        a3       : ko.observable(false),
        ...
        b1       : ko.observableArray([]),
        b2       : ko.observableArray([]),
    };


    this.someMethod = function(ID){
        $.post('/url', { ... }, function(o){
            self.type1.a1(o['a1']);
            ...
            self.type1.b1(o['b1']);
        }, 'json');
    }

As you see I am assigning all the values from ajax response to my model. I can make sure that result from ajax has the same fields (a1 ... b1) but there can be more fields than are available in type1.

There is nothing wrong with my code, it works fine, but I just think that all this code inside of my post request could be simplified. I looked into Loading and Saving data in knockout, but was not able to find anything suited. Another option I have is to iterate through type1 and extract the same values from o, but is there anything knockout specific out there?

P.S. if you know a better title for this post - please edit it.

¿Fue útil?

Solución

Use the mapping plugin

From the docs:

This automatically creates observable properties for each of the properties on data. Then, every time you receive new data from the server, you can update all the properties on viewModel in one step by calling the ko.mapping.fromJS function again

So your method would become:

this.someMethod = function(ID){
    $.post('/url', { ... }, function(o){
        ko.mapping.fromJS(o, self);
    }, 'json');
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top