将Knockout js json转换为observable

时间:2013-02-24 12:26:06

标签: javascript json knockout.js

我正在努力返回JSON数据并将其转换为可观察的数据。数据以JSON格式返回,但似乎没有分配给observable。有人可以帮忙吗?我猜这个问题是在ajax调用的成功部分:

<script type="text/javascript">

function StandingsViewModel() {
    var self = this;

    self.standings = ko.observableArray();

    self.DivisionName = ko.observable('');

    self.afceast = ko.computed(function () {

        return ko.utils.arrayFilter(self.standings(), function (i) {
            return "AFC East" == i.DivisionName;
        });
    });

    self.afccentral = ko.computed(function () {

        return ko.utils.arrayFilter(self.standings(), function (i) {
            return "AFC Central" == i.DivisionName;
        });
    });

    self.afcwest = ko.computed(function () {

        return ko.utils.arrayFilter(self.standings(), function (i) {
            return "AFC West" == i.DivisionName;
        });
    });

    self.nfceast = ko.computed(function () {

        return ko.utils.arrayFilter(self.standings(), function (i) {
            return "NFC East" == i.DivisionName;
        });
    });

    self.nfccentral = ko.computed(function () {

        return ko.utils.arrayFilter(self.standings(), function (i) {
            return "NFC Central" == i.DivisionName;
        });
    });

    self.nfcwest = ko.computed(function () {

        return ko.utils.arrayFilter(self.standings(), function (i) {
            return "NFC West" == i.DivisionName;
        });
    });

    $.ajax({
        dataType: "json",
        url: "/api/standing/GetStandingsBySeason/2018",
        beforeSend: function (xhr) {
            $('#divStandings').html('');
            $('#divStandings').addClass('ajaxRefreshing');
            xhr.setRequestHeader('X-Client', 'jQuery');
        },
        success: function (result) {
            $('#divStandings').removeClass('ajaxRefreshing');
            self.standings(JSON.parse(result));
        }
    });
}

$(document).ready(function () {
    ko.applyBindings(new StandingsViewModel());
});

</script>

2 个答案:

答案 0 :(得分:11)

您应该使用Knockout Mapping插件并将结果映射到observable。

var observableData = ko.mapping.fromJS(result);

或者如果你的对象没有被jQuery自动解析

var observableData = ko.mapping.fromJSON(result);

如果您的数据类型是数组,它将转换为observableArray,因此要将它作为普通数组获取,您可以通过添加括号从任何其他可观察数据获得;

var array = observableData();

该数组可以通过这种方式分配给你的obsevableArray:

self.standings(array);

答案 1 :(得分:1)

使用Knockout的映射插件的另一种选择是使用Knockback。它是Knockout与Backbone之间的桥梁。

您可以轻松获取数据:

//Model
var StandingsModel = Backbone.Collection.extend({ 
    url:'/api/standing/GetStandingsBySeason/2018' 
});

//View model
var StandingsViewModel = function (standings) {
    this.standings = kb.collectionObservable(standings)
    //...
};

$(document).ready(function () {
    //Get data from server
    var model = new StandingsModel();
    model.fetch( function() {
        success: //...
    });

    //Apply bindings
    ko.applyBindings(new StandingsViewModel(model));
});