Search code examples
javascriptloggingknockout.jssubscribeko.observablearray

Is it possible to log a KO observable array?


I am new to knockoutjs and I have an uber-basic question for you:

I have been able to successfully subscribe to a user changing the on screen twitter handle AND successfully fetch the tweets and display the last recent tweet of a user using console.log(json.results[0].text); However I am not confident that my observable array is working, when I push the json.results into recent tweets: recent_tweets.push(json.results[0].text) I see an [] empty array.

What is going on? Is logging ko.observable array possible?

console.log("TwitterFeedComponent loaded")
TwitterFeedComponent = function(attributes) {
  if (arguments[0] === inheriting)
    return;

  console.log("TwitterFeedComponent() loaded")

  var component = this;  
  var url = 'https://twitter.com/search.json?callback=?';

  this.attributes.twitter_user_handle.subscribe(function(value) {
  alert("the new value of the twitter handle is " + value);
  console.log("I have loaded")

    var url = 'https://twitter.com/search.json?callback=?';
    var twitter_parameters = {
      include_entities: true,
      include_rts: true,
      q: 'from:' + value,   
      count: '3'
    }

  $.getJSON(url,twitter_parameters, 
  function(json) {
      result = json.results[0].text
      recent_tweets.push(json.results[0].text);
      console.log(recent_tweets);
      console.log(json.results[0].text);

  });

 }); 
};

Solution

  • To access the actual values of an observable whether it's an array or not you need include parenthesis. For example the following will work:

    var recent_tweets= ko.observableArray(["hello", "hi", "how are you"]);
    console.log(recent_tweets());
    

    The same is true when assigning variables.

    Here is an example of a regular scalar value:

    var myObservableName = ko.observable("Luis");
    myObservableName("Dany"); // changes the name to: Dany
    var Name = myObservableName(); // gets the value and assigns it to the variable Name (in    this case the value is "Dany")