簡體   English   中英

如何在敲除js組件中添加Twitter Twitter跟隨按鈕?

[英]How to add a twitter follow button inside a knockout js component?

我在我的網站上使用基因敲除.js組件。 我想在我的組件之一中添加一個Twitter Follow按鈕。 如您所知,twitter提供了一個片段,可以使用腳本來做到這一點。

<a href="https://twitter.com/vishnu_narang" class="twitter-follow-button" data-show-count="false">Follow
        @vishnu_narang</a>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

該代碼段應該使用iframe和小部件腳本執行的其他操作來添加twitter twitter按鈕。

在組件外部可以正常工作。 例:

<html>
  <body>
    // Snippet here will work as expected
  </body>
</html>

但是在淘汰賽js組件中,它不起作用:

例如:

<html>
  <body>
    <profile></profile>
  </body>
</html>

// Profile template will be
<div>
   //snippet for follow button here.
</div>

有人可以幫我找到在這種組件內成功添加關注按鈕的方法嗎?

注意:我也在使用require.js和gulp。 Facebook之類的按鈕呈現良好。

twitter小部件javascript一旦加載,便立即掃描DOM以查找需要轉換為小部件的元素。 由於您是在組件中動態加載元素,因此在Twitter javascript完成之前,它實際上並不存在於DOM中。

為了解決這個問題,您可以通過從組件的視圖模型函數調用twttr.widgets.load()來強制窗口小部件再次掃描dom。 參考

示例: jsFiddle

它不起作用,因為配置文件標記是動態插入的,並且在加載twitter小部件腳本時DOM中不存在a元素。

您可以做的是編寫一個自定義綁定,該綁定為元素運行Twitter初始化功能。 看一下這個片段:

 ko.components.register('profile', { viewModel: function() { }, template: '<a href="https://twitter.com/TwitterDev" class="twitter-follow-button" data-show-count="true" data-bind="twitterWidget">Follow @vishnu_narang</a>' }); ko.bindingHandlers.twitterWidget = { init: function(element, valueAccessor, allBindings, viewModel, bindingContext) { twttr.widgets.load(element) } }; ko.applyBindings({}) 
 <html> <head> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> </head> <body> <profile></profile> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM