0

我使用这个修改后的示例代码从 twitter api 中提取一些数据并将结果设置为 viewModel

var myModel = new MyViewModel();
// Handler for .ready() called.
function MyViewModel(){

      this.show_search = ko.observable(true); // Message initially visible
      this.show_player = ko.observable(false);  // Message initially visible 

      this.tweetSearchKeyWord = ko.observable("google");
      this.currentTweets = ko.observableArray([]);

      this.showSearch = function(){

        this.show_search(true);
        this.show_player(false);
      };

      this.showPlayer  = function(){

        this.show_search(false);
        this.show_player(true);
      };
};

ko.computed(function () {
  $.getJSON("http://search.twitter.com/search.json?q=%23" +     myModel.tweetSearchKeyWord()+"&callback=?", function (data) {

      theData = data.results;
      myModel.currentTweets(theData);

  });
}, viewModel );


ko.applyBindings( myModel );

数据接收良好,data.results 显示 Array[15]

但是在我将它设置为模型之后

myModel.currentTweets(theData);

myModel.currentTweets 反映为一个空数组 []

知道有什么问题吗?

4

1 回答 1

0

There is no any need to use ko.computed because it works differently. What you need to do is just to specify any event handler and fill up the data there. Something like that:

somewhere in html:

<button data-bind="click:getData">Get</button>

in js:

function getData()
{
    $.getJSON("http://search.twitter.com/search.json?q=%23" +            myModel.tweetSearchKeyWord()+"&callback=?", function (data) {

      myModel.currentTweets(data.results);

  });
}

Or, if you want to update data after the definite time interval, use setTimeout() JavaScript function.

于 2013-02-24T00:52:44.353 回答