使用api获取并设置按钮点击的分析日志



我正在尝试存储按钮点击日志的用户级别,这样我就可以在我的项目中的某个地方使用它们了。你能帮助我并告诉我如何做到这一点吗?用户级别,使用api设置它们,并在需要时获取它们。我在前端使用svelte(使用firebase或类似的东西存储日志(。用户级别意味着每个用户将保存不同的数据,我可以使用userid通过使用userid 获取用户的详细信息

我建议将一些装饰器模式应用于感兴趣的事件处理程序。

假设您有一个按钮,并且想要记录on:click事件。您可以使用名为monitor的装饰器来装饰handleClick事件处理程序。

<script>
import { getContext, onMount } from "svelte"
const monitor = getContext("monitor")
function handleClick(event) {
// do stuff
}
</script>
<button on:click={monitor(handleClick)}>Click me</button>

现在,在根<App />组件中,应该初始化monitor装饰器并将其设置到上下文中。

<script> // App.svelte
import { setContext } from "svelte"
import { Login } from "./components/Login.svelte"
let userId = null
const setUserId = (id) => { userId = id }
// the decorator wraps the original eventHandler
// and smuggles in some report logic
function monitor(eventHandler) {
return function decoratedEventHandler() {
// if we have the userId, we can start to report event logs
if (userId) {
const event = arguments[0]
// impl report as you needed
// it can simply be a HTTP POST to some backend API
// I definitely suggest add some throttle mechanism into it
report(userId, event) 
}
eventHandler.apply(this, arguments)
}
}
setContext("monitor", monitor)
onMount(() => {
// if you store userId in cookie,
// you parse the cookie and restore it
userId = getUserIdFromCookie(document.cookie)
})
</script>
<!-- 
or maybe your Login component has some special logic
to get userId from backend
-->
<Login updateUserId={setUserId} ></Login>

相关内容

最新更新