升级模型 (backbone.js)
现在我有一个适用于所有用户的通用用户模型。当用户登录时,将确定他们是用户类型 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以这么做。您也可以只复制
attributes
:请注意,无论使用哪种方法,您都会丢失事件绑定等。更安全、更 JavaScript 的方法是仅扩展
user
code> 就地添加了其他方法,而不是根本没有Type1
类。 (当然,这样做也有缺点,例如失去从这些方法调用super
的能力。请参阅我对类似问题的回答 此处。)You could do that. You could also just copy over the
attributes
: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 aType1
class at all. (Of course, there are downsides to that to, such as losing the ability to invokesuper
from those methods. See my answer to a similar question here.)