我拥有使用其他平台/框架构建自定义解决方案的经验,并希望了解这是否是创建 Discourse 主题组件的正确方法。
它似乎有效,但这并不一定意味着它是正确的方法。
简而言之,这应该会隐藏某个主题所属类别的反应。这是正确的方法吗?
<script type="text/discourse-plugin" version="0.1">
$(document).ready(function() {
try {
const isTopicPage = /^\/t\//.test(window.location.pathname);
if (!isTopicPage) return;
const allowedCategories = ['ask-a-question'];
const topic = Discourse.__container__.lookup("controller:topic");
const categorySlug = topic && topic.get("model.category.slug");
const isAllowedCategory = categorySlug && allowedCategories.includes(categorySlug);
const toggleReactionEmoji = () => {
const emoji = document.querySelector("[data-reaction='frog']");
if (emoji) {
emoji.style.display = isAllowedCategory ? '' : 'none';
console.log(`Emoji with data-reaction='frog' ${isAllowedCategory ? 'shown' : 'hidden'}.`);
}
};
toggleReactionEmoji();
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === 1) {
const emoji = node.querySelector("[data-reaction='frog']");
if (emoji) {
emoji.style.display = isAllowedCategory ? '' : 'none';
console.log(`Emoji with data-reaction='frog' found in mutation and ${isAllowedCategory ? 'shown' : 'hidden'}.`);
}
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
api.cleanupStream(() => observer.disconnect());
} catch (error) {
console.error("An error occurred in the emoji toggle script:", error);
}
});
</script>