我正在尝试完成以下任务:
我有一个超级基本的问题。我有硬编码的HTML,我可以用knockouk获取推文,我想消除我的硬编码元素,只使用knockoutjs。我可以使用 subscribe 从用户Y获取x个推文,并使用可观察数组将推文推送到。
效果很好的代码。我是这样做的:
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);
});
});
};
我的问题很简单。这些推文住在这里:
现在我正在将每条推文静态插入到html中。如果用户只有3条推文并且我在硬件中编写了5条推文,则会中断。我怎样才能用户敲出来用推文插入html?
我希望消除的STATIC HTML示例,并替换为Knockout JS插入的动态HTML。
<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>
答案 0 :(得分:2)
一般的想法是使用Knockout的foreach
绑定和observbaleArray。而不是将结果推送到observableArray,您可能希望将其完全设置为新数组。
所以,而不是:
recent_tweets.push(result);
你会这样做:
recent_tweets(result);
以下是基于您的代码的示例,该示例公开了一些用于绑定的可观察对象:http://jsfiddle.net/rniemeyer/8kK6m/