简体   繁体   English

模型未在ko.compute中使用Knockout刷新

[英]model not refreshing inside ko.computed with Knockout

im using this modified example code to pull some data from twitter api and set the results to a viewModel 即时通讯使用此修改后的示例代码从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 is recieved fine, and data.results shows Array[15] 数据正常,并且data.results显示Array [15]

but after i set it to the model with 但是在我将其设置为模型后

myModel.currentTweets(theData);

myModel.currentTweets reflects as an empty array [] myModel.currentTweets反映为空数组[]

Any idea what's wrong? 知道有什么问题吗?

There is no any need to use ko.computed because it works differently. 不需要使用ko.computed,因为它的工作方式不同。 What you need to do is just to specify any event handler and fill up the data there. 您需要做的只是指定任何事件处理程序,并在那里填充数据。 Something like that: 像这样:

somewhere in html: html中的某处:

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

in js: 在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. 或者,如果要在确定的时间间隔后更新数据,请使用setTimeout()JavaScript函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM