繁体   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