簡體   English   中英

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

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

即時通訊使用此修改后的示例代碼從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反映為空數組[]

知道有什么問題嗎?

不需要使用ko.computed,因為它的工作方式不同。 您需要做的只是指定任何事件處理程序,並在那里填充數據。 像這樣:

html中的某處:

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

在js中:

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

      myModel.currentTweets(data.results);

  });
}

或者,如果要在確定的時間間隔后更新數據,請使用setTimeout()JavaScript函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM