2015-12-18 141 views
0

使用Knockout,我試圖用鼠標懸停上的JSON對象的值更新數據綁定的值。我覺得我在這裏基本缺乏理解。我哪裏錯了?Knockout.js:從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

我想這是你所需要的:

(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));