通过html类维护JavaScript中的状态 [英] Maintaining state in javascript through html class

查看:62
本文介绍了通过html类维护JavaScript中的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个用户可以为某些地点添加书签的网络应用。

为此我创建了一个 span 元素,它最初有一个类 no-书签。每当用户点击这个span元素时,我会检查span是否具有上述类别。如果有,则表示用户想为书签添加书签,然后向服务器发送ajax请求,然后将该类更改为 has-bookmark



如果用户点击跨度并且没有类 no-bookmark ,那么我假设用户想要删除书签,并向服务器发送请求。



有没有更好的方法来维护状态,或者这种方法足够好?

解决方案

这并不是太糟糕的方法,尽管它将逻辑和UI混合在一起,这很难保持长期。

尽管如此。如果您提交请求(是否设置或删除书签)会发生什么情况,并会失败?然后你的课堂与现实不协调。



你还需要记住其他的东西可能会改变CSS类。任何方式的客户端代码都可能会改变这些类,所以请谨慎。



当用户关闭页面然后重新打开页面时会发生什么?除非你不关心长期状态,否则你还需要另外设置一些设置。



如果您关心长期状态,您可以使用Cookie,本地存储或实际上是后端存储来维护该状态,具体取决于系统的设计。在这种情况下,尝试在类中纯粹维护状态可能没有任何好处,但在JS变量中跟踪状态会更健壮,尽管该类可能仍然有用,但仅用于UI目的。



你可以看看REACT这样的东西来帮助你处理这些事情。以一些初始负载重量为代价,您在维护状态和被动方面获得了很多帮助。

I'm creating a web app in which users can bookmark certain places.

For this I've created a span element which initially has a class no-bookmark. Whenever a user clicks this span element I would check whether the span has the above class or not. If it has it means the user wants to bookmark the place and I would send a ajax request to server and then change the class to has-bookmark.

If when the user clicks the span and it doesn't have the class no-bookmark, then I assume that the user wants to delete the bookmark, and send a request for that to the server.

Is there a better way to maintain state, or is this method good enough?

解决方案

It isn't too bad way a to do it though it does mix logic with the UI which can be difficult to maintain long term.

One catch though. What happens if you submit a request (whether to set or delete the bookmark) and it fails? Then your class is out of step with reality.

You also need to remember that other things could change the CSS class. Any manner of client-side code could change the classes so be wary of that too.

Also what happens when the user closes the page and later reopens it? You still have to have another setting somewhere to track unless you don't care about longer-term state.

If you do care about long-term state, you could use cookies, local storage or indeed back-end storage to maintain that state depending on the design of your system. In that case, there is probably no benefit in trying to maintain the state purely in the class, it would be more robust to track state in a JS variable though the class is probably still useful but only for UI purposes.

You could look at something like REACT to help you with these things. At the cost of some initial load "weight", you get a LOT of help with maintaining state and being reactive.

这篇关于通过html类维护JavaScript中的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆