Question

I am trying to accomplish the following task:

  1. List item
  2. Get a twitter handle
  3. Ask user how many tweets to display
  4. Fetch tweets
  5. Display only the tweets the user has specified

I have a super basic problem. I have hard coded html and I can fetch tweets with knockouk, I'd like to eliminate my hardcoded element and only use knockoutjs. I can fetch x number of tweets from user Y using subscribe and I use the observable array to push tweets into.

Code that works fantastic. Here is how I do it:

TwitterGet = function() {
  var recent_tweets = ko.observableArray();
  var twitter_image = ko.observable();

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

  this.attributes.twitter_user_handle.subscribe(function(value) {

    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) {
    twitter_image(json.results[0].profile_image_url);
      result = json.results;
      recent_tweets.push(result);
  });
 }); 
};

My problem is uber simple. The tweets live here:

  1. recent_tweets.slice(-1)[0][0].text (first tweet)
  2. recent_tweets.slice(-1)[0][1].text (second tweet)

Right now I am statically plugging each tweet into html. This breaks if the user only has 3 tweets and I have hard coded 5 tweets into the html. How can I user knockout to insert html with the tweet?

Example of STATIC HTML that I would like to eliminate, AND replace with dynamic HTML inserted by Knockout JS.

<div class="tweet" id="first-tweet">
<span class="handle"><a href="#" target="_blank" data-bind-component_<%=component.id-%>="inline_edit: attributes.twitter_user_handle"></a> 
</span><span data-bind-component_<%=component.id-%>="inline_edit: recent_tweets.slice(-1)[0][1].text"></span><br>
<a href="#">share</a>
<a href="#" target="_blank">retweet</a> 
<a href="#">reply</a></div>

<div class="tweet" id="second-tweet">
<span class="handle"><a href="#" target="_blank" data-bind-component_<%=component.id-%>="inline_edit: attributes.twitter_user_handle"></a> 
</span><span data-bind-component_<%=component.id-%>="inline_edit: recent_tweets.slice(-1)[0][2].text"></span><br>
Was it helpful?

Solution

The general idea would be to use the foreach binding of Knockout with an observbaleArray. Rather than pushing the result into the observableArray, you would want to set it entirely to a new array.

So, instead of:

recent_tweets.push(result);

You would do:

recent_tweets(result);

Here is a sample based on your code that exposes some of the observables for binding: http://jsfiddle.net/rniemeyer/8kK6m/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top