我需要在GWT应用程序中使用Disqus,因此我需要解决按需加载线程的问题,因为应用程序中的虚拟页面正在更改。
进行了少量的逆向工程和实验后,我构建了一个实用类(如下所示)。
主要见解如下:
- 有一个未记录的全局参数叫做
disqus_container_id
,它允许您将评论放在任何您喜欢的地方。如果在将来的某个版本中无法使用,我的备选方案是暂时将目标元素的ID设置为disqus_thread
,添加评论,然后将其改回原始ID。
- 由于这是使用JSNI开发GWT的,我需要在原始窗口上下文中设置全局参数,通过
$wnd
可访问。我相应地更改了默认的Disqus嵌入代码。我之前没有意识到所有全局变量都在Window对象中,但我学到了一些新东西。
- 您可以重复使用相同的容器,Disqus似乎会在激活时清除内容。
- 这会在DOM中留下许多脚本标记的副本。也许在使用后清理这些副本是个好主意。或者,我可能会进行更多实验,使用其他答案中描述的
DISQUS.reset
方法。
仅提取对于单独使用JS的人来说至关重要的信息,这应该允许您将Disqus线程粘贴到任何您喜欢的地方:
function loadComments(container_id, shortname, identifier, developer) {
window.disqus_container_id = container_id;
window.disqus_developer = developer ? 1 : 0;
window.disqus_shortname = shortname;
if (identifier) window.disqus_identifier = identifier;
(function() {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = 'http://' + shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
}
这里是完整的GWT实用类。到目前为止,我只实现了我需要的参数。
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Widget;
public class Disqus {
public static boolean developer = false;
public static String shortname;
public static void showComments(Widget where, String identifier) {
showComments(where.getElement(), identifier);
}
public static void showComments(Element where, String identifier) {
if (shortname == null)
throw new IllegalArgumentException(
"You must specify the disqus shortname before displaying comments");
String id = where.getId();
if (id == null) {
id = "disqus-" + Integer.toHexString(Random.nextInt());
where.setId(id);
}
where.setId("disqus_thread");
loadComments(id, shortname, identifier, developer);
}
private static native void loadComments(String container_id, String shortname, String identifier, boolean developer) ;
}