Knockout.js:从JSON获取可观察量的值

时间:2015-12-18 03:07:49

标签: javascript jquery json knockout.js data-binding

使用Knockout,我尝试使用鼠标悬停时JSON对象的值更新数据绑定的值。我觉得我在这里缺乏理解。我哪里错了?

(function($, ko, test) {
    var self = this;
    self.text = ko.observable();

    var MV = function() {

        $.getJSON('data.json')
        .then(function (data) {
            self.data = data;
            return self.data;
        });

        self.mouseOver = function() {
            self.text = ko.observable(self.data[0]);
        }

    };

    $(function() {
        test.mv = new MV();
        ko.applyBindings(test.mv, document.getElementById('wrapper'));
    });

}(jQuery, ko, window));

1 个答案:

答案 0 :(得分:1)

我认为这就是你所需要的:

(function($, ko, test) {
    var MV = function() {
        var self = this;
        self.text = ko.observable();
        self.data = ko.observableArray();
        $.getJSON('data.json')
        .then(function (data) {
            self.data(data);
        });

        self.mouseOver = function() {
            self.text(self.data()[0]);
      }

  };

    $(function() {
        test.mv = new MV();
        ko.applyBindings(test.mv, document.getElementById('wrapper'));
    });

}(jQuery, ko, window));