【问题标题】:Knockoutjs super basicsKnockoutjs 超级基础
【发布时间】:2012-02-18 05:27:51
【问题描述】:

我正在尝试完成以下任务:

  1. 列表项
  2. 获取推特句柄
  3. 询问用户要显示多少条推文
  4. 获取推文
  5. 仅显示用户指定的推文

我有一个超级基本的问题。我有硬编码的html,我可以用knkouk获取推文,我想消除我的硬编码元素,只使用knockoutjs。我可以使用 subscribe 从用户 Y 获取 x 条推文,并使用 observable 数组 将推文推送到其中。

非常棒的代码。这是我的做法:

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);
  });
 }); 
};

我的问题非常简单。推文住在这里:

  1. recent_tweets.slice(-1)[0][0].text(第一条推文)
  2. recent_tweets.slice(-1)[0][1].text(第二条推文)

现在我将每条推文静态插入到 html 中。如果用户只有 3 条推文并且我已将 5 条推文硬编码到 html 中,则会中断。如何通过用户敲除插入带有推文的 html?

我想消除的静态 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>

【问题讨论】:

    标签: javascript knockout.js observable subscribe


    【解决方案1】:

    一般的想法是使用带有 observbaleArray 的 Knockout 的 foreach 绑定。与其将结果推入 observableArray,不如将其完全设置为一个新数组。

    所以,而不是:

    recent_tweets.push(result);
    

    你会这样做:

    recent_tweets(result);
    

    这是一个基于您的代码的示例,该示例公开了一些可观察的用于绑定:http://jsfiddle.net/rniemeyer/8kK6m/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 2013-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多