升级模型 (backbone.js)

发布于 2024-12-04 19:21:01 字数 446 浏览 1 评论 0原文

现在我有一个适用于所有用户的通用用户模型。当用户登录时,将确定他们是用户类型 1 还是用户类型 2。这两种类型需要完全不同的模型来表示它们,但仍然包含通用用户模型中找到的所有内容。

我的目标是通过将状态从当前用户模型传递到 Type1 或 Type2 模型来升级每种类型用户的用户模型。

(在咖啡脚本中)

class Type1 extends User
    #add super set of methods


#user arrives

user = new User

#after logging in

state = user.toJSON()

#do I need to unbind/delete the current user model?

user = new Type1(state)

这是实现这一目标的最佳方法吗?

谢谢!

Right now I have a generic User model for all users. When a user logs it's determined wether they are user type 1 or user type 2. These two types need totally different models to represent them but still include everything found in the generic User model.

My goal is up upgrade the User model for each type of user by passing the state from the current User model into the Type1 or Type2 model.

(in coffeescript)

class Type1 extends User
    #add super set of methods


#user arrives

user = new User

#after logging in

state = user.toJSON()

#do I need to unbind/delete the current user model?

user = new Type1(state)

Is this the best way to achieve this?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

━╋う一瞬間旳綻放 2024-12-11 19:21:01

你可以这么做。您也可以只复制 attributes

userCopy = new Type1
userCopy.attributes = user.attributes
delete user

请注意,无论使用哪种方法,您都会丢失事件绑定等。更安全、更 JavaScript 的方法是仅扩展 user code> 就地添加了其他方法,而不是根本没有 Type1 类。 (当然,这样做也有缺点,例如失去从这些方法调用 super 的能力。请参阅我对类似问题的回答 此处。)

You could do that. You could also just copy over the attributes:

userCopy = new Type1
userCopy.attributes = user.attributes
delete user

Note that with either approach, you'll lose event bindings, etc. A safer, more JavaScript-y approach would be to just extend user in-place with additional methods, rather than having a Type1 class at all. (Of course, there are downsides to that to, such as losing the ability to invoke super from those methods. See my answer to a similar question here.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文