Reputation: 21877
I am trying to accomplish the following task:
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:
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>
Upvotes: 1
Views: 547
Reputation: 114792
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/
Upvotes: 2