简体   繁体   中英

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

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]

but after i set it to the model with

myModel.currentTweets(theData);

myModel.currentTweets reflects as an empty array []

Any idea what's wrong?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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