【问题标题】:Knockout.js: Getting values of observables from JSONKnockout.js:从 JSON 中获取 observables 的值
【发布时间】:2016-03-24 17:01:57
【问题描述】:

使用 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));

【问题讨论】:

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


    【解决方案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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2012-09-27
      • 2014-08-02
      相关资源
      最近更新 更多