1

I have a list of JSON models that I'm receiving from the server via AJAX.

I don't want to have to redefine my models as functions in JavaScript as well.

How can I prevent having to do below? I still want all the model properties to be observable though.

function Car(car) {

    this.Name = ko.observable(car.Name);
    this.Type = ko.observable(car.Type);
    this.Rating = ko.observable(car.Rating);
    this.Color = ko.observable(car.Color);
}

var ViewModel = function () {

    var self = this;
    self.cars = ko.observableArray([]);

    $.post('/car/getall', function (cars) {

        var carsKO= [];
        $.each(cars, function (i, elm) {

            carsKO.push(new Car(elm));
        });

        self.cars(carsKO);
    });
};

ko.applyBindings(new ViewModel());

People are talking about Knockout Mapping plugin. But I fail to see how that would get me any different than below? At this point I wouldn't have the model properties observable.

var ViewModel = function () {

    var self = this;
    self.cars = ko.observableArray([]);

    $.post('/car/getall', function (cars) {

        self.cars(cars);
    });
};

ko.applyBindings(new ViewModel());
4

1 回答 1

2

您应该像这样使用 ko.mapping 的 fromJS函数

var ViewModel = function () {

    var self = this;
    self.cars = ko.observableArray([]);

    $.post('/car/getall', function (cars) {
        ko.mapping.fromJS(cars, {}, self.cars);
    });
};

我希望它有所帮助。

于 2013-06-26T19:16:24.790 回答